package com.scalar.chiptrack.workflow;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.FlowLayout;
import java.awt.Color;
import java.awt.Font;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.EventObject;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.swing.AbstractCellEditor;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

import com.jgraph.graph.DefaultEdge;
import com.jgraph.graph.DefaultGraphCell;
import com.jgraph.graph.GraphConstants;


public class PopupPanel extends JPanel
{
	protected JTextField partNumberField;
	protected JTextField mktPartNumberField;
	protected JTextField processNameField;
	protected JTextField goodBinField;
	protected JTextField rejectedBinField;
	protected JCheckBox binsRequiredCheckBox;
	protected JCheckBox approvedCheckBox;
	protected JCheckBox isPrimaryFGCheckBox;
	protected JComboBox availableProcessTypes;	// Stores all the Available processes and Parameters
	protected JTextArea	comments;
	protected JButton addButton;
	protected JButton deleteButton;
    protected JComboBox partStatusField;
    protected JComboBox productGroupField;

    protected JTableX table;
	protected JTable partNumberTable;
	protected JTable vendorTable;
	protected JTable transportTable;
    protected JTable bomPartsTable;

	protected JFrame frame;

	protected JPanel mktPanel;
	protected JPanel binRequiredPanel;
	protected JPanel binPanel;
	protected JPanel approvedProductPanel;
	protected JPanel isPrimaryFGPanel;
	protected JPanel vendorPanel;
	protected JPanel commentPanel;
	protected JPanel mainPanel;
	protected JPanel rootPanel;
	protected JPanel transportPanel;

	protected JScrollPane scrollPane;
	protected JScrollPane mainScrollPane;

	protected ActionHandler handler;
    protected KeyHandler keyHandler;
	protected Component editComponent;

	protected DefaultGraphCell cell;		// The cell from which this window is invoked
	protected DefaultGraphCell sourceCell;	// The Source cell in transition
	protected DefaultGraphCell targetCell;	// The target cell in transition
	protected WorkflowGraph graph;			// Jgraph object
	protected Map attributes;				// Carries the Attributes of the Cell on which popup panel is invoked
	protected Map sourceAttributes = null;	// Carries the source cell attributes
	protected Map targetAttributes = null;	// Carries the target cell attributes

	protected String type 				= null;
	protected String baseProcessType 	= null;
	protected static String separator			= "#$#$#$";
    protected HashMap vendorLocationsMap 	= new HashMap();
	protected HashMap processParametersMap  = new HashMap();
	protected HashMap newPartNumberMap		= null;

	VendorTableModel  vendorTableModel 		= new VendorTableModel();
	ParameterTableModel parameterTableModel = new ParameterTableModel();
	TrasportTableModel transportTableModel	= new TrasportTableModel();
    BOMPartsTableModel bomPartsTableModel	= new BOMPartsTableModel();

	MultiLineHeaderRenderer renderer = new MultiLineHeaderRenderer();
	CustomTableCellRenderer customTableCellRenderer = new CustomTableCellRenderer();
    ArrayList vendorsWithLots = null;    //Contains List Of Vendors having Lots (Running or Hold ) for this Process.
    //String[] package_types = { "ABC", "HORIZONTAL", "VERTICAL", "BOTH" };
    Vector package_types = null;

    HashMap comboMap = null;

	// This constructor is for Default cell
	public PopupPanel( JFrame frame, Component editComponent, Object cell, WorkflowGraph graph )
	{
		// Fetch the screen Dimensions
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        // Set the width and Height
        int width 			= ( new Double( dimension.getWidth()*65/100) ).intValue();
        int height 			= ( new Double( dimension.getHeight()*80/100) ).intValue();
        // Main Panel
		mainPanel 			= new JPanel();
		mainScrollPane 		= new JScrollPane( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS , JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );

        this.setPreferredSize( new Dimension( width, height ) );
        // Set the ScrollPane Size to fit into the window in all resolutions.
		mainScrollPane.setPreferredSize( new Dimension( width, height ) );
        // Initalize the Actional Handler
		handler = new ActionHandler();
        keyHandler = new KeyHandler();
		// This fetches the cell from which the popup panel is intiated
		this.cell 	= (DefaultGraphCell)cell;
		// This fetches the JGraph Object
		this.graph 	= graph;
		this.frame 	= frame;
		newPartNumberMap = graph.editor.getNewPartNumberMap();
		// the component where the mouse is clicked..
		// Usefull to set focus to the component after saving the popup panel
		this.editComponent = editComponent;
		// This fetches all the attributes of the cell. The XPDL details
		attributes = this.cell.getAttributes();
		// PopupPanel get initiated only if clicked on a cell
		if( cell instanceof DefaultGraphCell )
		{
			// if the cell is not a Transition then
			if( !( cell instanceof DefaultEdge ) )
			{
                Map activityAttributesMap = null;
                if ( attributes.containsKey( "processStepId" ) && attributes.get( "processStepId" ) != null && ( (String)attributes.get( "processStepId" ) ).length() > 0 )
                {
                    activityAttributesMap = getActivityAttributesMap( (String)attributes.get( "processStepId" ), graph );
                }
                if ( activityAttributesMap != null )
                {
                    attributes.putAll( activityAttributesMap );
                }
                // Should be moved to Editor.java ************  getDefaultVendorLocations() :: getProcessParameters()
				// This fetches all the VendorLocations Map
				getDefaultVendorLocations();
				// This fetches all the Process Parameters Map
				getProcessParameters();
                //This is for loading the Package Types.
                //getPackageTypes();

                //This fetches List Of the Vendors having Lots ( Running or Hold ) for this Process
                if ( attributes.containsKey( "processStepId" ) && attributes.get( "processStepId" ) != null && ( (String)attributes.get( "processStepId" ) ).trim().length() > 0 )
                {
                    getVendorsWithLots( (String)attributes.get( "processStepId" ) );
                }

				// set the type to process type and baseProcessType to base process
				if( attributes.get( "Type" ) != null  )
				{
					baseProcessType = (String) attributes.get( "Type" );
				}

				if( attributes.get( "value" ) != null  )
				{
					type = (String) attributes.get( "value" );
				}
				/*if( attributes.get( "name" ) != null  )
				{
					type = (String) attributes.get( "name" );
				}*/

                getComboMap();

				mainPanel.setLayout( new BoxLayout( mainPanel, BoxLayout.Y_AXIS ) );
				// Fetches the PartNumber & Name and Process Panel
				mainPanel.add( getTopPanel() );
				// Fetches the Equivalent Part Numbers and Comments Panel
				mainPanel.add( getDupPartNumberPanel() );
				// Fetches the Process Parameters
				mainPanel.add( getParameterPanel() );
				// Fetches the Vendors and Vendor Information
				mainPanel.add( getVendorPanel() );

                if ( availableProcessTypes != null && !"select process".equalsIgnoreCase( (String) availableProcessTypes.getSelectedItem() )
                        && attributes.containsKey( "partnumber" )
                        && attributes.get( "partnumber" ) != null && "clipboard".equalsIgnoreCase((String)attributes.get( "partnumber" ) ) ) 
                {                       
                    setVendorTable  ( baseProcessType );
                    setVendorDetails( baseProcessType );
                    reloadParameterTable( (String) availableProcessTypes.getSelectedItem() );
                }
                // Fetches the BOM Parts
                if( baseProcessType != null && ( baseProcessType.equalsIgnoreCase("assembly") || baseProcessType.equalsIgnoreCase("sort") ) )
                {
                    JPanel bomPartsPanel = getBomPartsPanel();
                    if( bomPartsPanel != null )
                    {
                        mainPanel.add(bomPartsPanel);
                    }
                }

				// Fetches the Ok, Cancel buttons in popup panel
				mainPanel.add( getBottomPanel() );
				mainScrollPane.getViewport().add( mainPanel );
				add( mainScrollPane );
			}
		}
    }

	// This constructor is for default Edge (Transition)
	public PopupPanel( JFrame frame, Component editComponent, Object cell, Object sourceCell, Object targetCell, WorkflowGraph graph )
	{
		Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
		int width 			= ( new Double( dimension.getWidth()*65/100) ).intValue();
		int height 			= ( new Double( dimension.getHeight()*80/100) ).intValue();
		mainPanel 			= new JPanel();
		mainScrollPane 		= new JScrollPane( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS , JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );

		this.setPreferredSize			( new Dimension( width, height ) );
		mainScrollPane.setPreferredSize	( new Dimension( width, height ) );
		handler 		= new ActionHandler();
		this.cell 		= (DefaultGraphCell)cell;
		this.sourceCell = (DefaultGraphCell)sourceCell;
		this.targetCell = (DefaultGraphCell)targetCell;
		this.graph 		= graph;
		this.frame 		= frame;
		this.editComponent 	= editComponent;
		attributes 			= this.cell.getAttributes();
		sourceAttributes 	= this.sourceCell.getAttributes();
		targetAttributes 	= this.targetCell.getAttributes();

		if( cell instanceof DefaultEdge )
		{
            mainPanel.setLayout( new BoxLayout( mainPanel, BoxLayout.Y_AXIS ) );
			// Fetches the Transport Locations Panel
			mainPanel.add( getTransportationPanel() );
			// Fetches the Ok, Cancel buttons in popup panel
			mainPanel.add( getBottomPanel() );
			mainScrollPane.getViewport().add( mainPanel );
			add( mainScrollPane );
		}
	}

    private Component getTransportationPanel()
    {
		transportPanel = new JPanel();
		transportPanel.setLayout( new BoxLayout( transportPanel,  BoxLayout.X_AXIS ) );
		transportPanel.setBorder( BorderFactory.createCompoundBorder(
						BorderFactory.createTitledBorder( "Transport Information" ),
						BorderFactory.createEmptyBorder( 1, 1, 1, 1 ) ) );

		scrollPane = new JScrollPane( getTransportTable() );
		transportPanel.add( scrollPane );
		return transportPanel;
    }

    private JTable getTransportTable()
    {
		transportTable	= new JTable( transportTableModel , new CustomTableColumnModel() , new DefaultListSelectionModel() );
		transportTable.setDefaultRenderer( Object.class, customTableCellRenderer );

		transportTable.addColumn( new TableColumn()	{
			public void setHeaderValue(Object headerValue){
				super.setHeaderValue("Source\n");
				setHeaderRenderer( renderer );
			}
		});

		transportTable.addColumn( new TableColumn()	{
			public void setHeaderValue(Object headerValue){
				super.setHeaderValue("Destination\n");
				setHeaderRenderer( renderer );
			}
		});

		transportTable.addColumn( new TableColumn()	{
			public void setHeaderValue(Object headerValue){
				super.setHeaderValue("Normal\nShipping Time");
				setHeaderRenderer( renderer );
			}
		});

		transportTable.addColumn( new TableColumn()	{
			public void setHeaderValue(Object headerValue){
				super.setHeaderValue("Express\nShipping Time");
				setHeaderRenderer( renderer );
			}
		});

		transportTable.addColumn( new TableColumn()	{
			public void setHeaderValue(Object headerValue){
				super.setHeaderValue("Normal\nShipping Cost");
				setHeaderRenderer( renderer );
			}
		});

		transportTable.addColumn( new TableColumn()	{
			public void setHeaderValue(Object headerValue){
				super.setHeaderValue("Express\nShipping Cost");
				setHeaderRenderer( renderer );
			}
		});

		Vector transportLocationData = getTransportData();
		Iterator it 	= transportLocationData.iterator();

		transportTableModel.setColumnCount( transportTable.getColumnCount() );
		transportTableModel.setColumnIdentifiers( getColumnIdentifiers( transportTable ) );

		while( it.hasNext() )
		{
			Vector rowData = (Vector) it.next();
			transportTableModel.insertRow( 0 , rowData );
		}

		transportTable.createDefaultColumnsFromModel();

		Enumeration enums = transportTable.getColumnModel().getColumns();
		TableColumn tableColumn;

		while (	enums.hasMoreElements() )
		{
			tableColumn = (TableColumn)enums.nextElement();

			tableColumn.setHeaderRenderer( renderer );
		}

		transportTable.getSelectionModel().addListSelectionListener( new ListSelectionListener(){
		protected TableColumn col;
		public void valueChanged(ListSelectionEvent e)
		{
			if( transportTable.getSelectedColumn() > 0)
			{
				transportTable.removeEditor();
				col = transportTable.getColumnModel().getColumn( transportTable.getSelectedColumn() );
				col.setCellEditor( new TransportTableCellEditor() );
			}
		}});
		transportTable.setPreferredScrollableViewportSize( new Dimension( 620, 150 ) );

		transportTable.invalidate();
		transportTable.validate();
		transportTable.repaint();
		return transportTable;
    }

    /**
     *	This Method returns the Transport location data
     *	depending on the Source and Destination Vendor locations selected.
     */
    private Vector getTransportData()
    {
    	Vector transportDataList	= new Vector();
        Vector transportData 		= null;
        Vector sourceVendorVector 	= null;
        Vector targetVendorVector	= null;
        Iterator sourceIterator		= null;
        Iterator targetIterator		= null;
        String sourceLocation		= null;
        String targetLocation		= null;
        Vector transportDataVector	= null;

        if( sourceAttributes != null && sourceAttributes.containsKey( "vendors" ) )
        {
        	sourceVendorVector = getVendorsLocationVector( (String) sourceAttributes.get( "vendors" ) );
        }

		if( targetAttributes != null && targetAttributes.containsKey( "vendors" ) )
		{
			targetVendorVector = getVendorsLocationVector( (String) targetAttributes.get( "vendors" ) );
		}

		// Fetch already saved data
		if( attributes != null && attributes.containsKey( "transportLocations" ) )
		{
			transportDataVector = getTransportActivityData( (String)attributes.get( "transportLocations" ) );
		}

        if( sourceVendorVector != null && sourceVendorVector.isEmpty() == false && targetVendorVector != null && targetVendorVector.isEmpty() == false )
        {
        	sourceIterator = sourceVendorVector.iterator();

        	while( sourceIterator.hasNext() )
        	{
				targetIterator = targetVendorVector.iterator();
				sourceLocation = ( String )sourceIterator.next();
				while( targetIterator.hasNext() )
				{
					targetLocation	= (String)targetIterator.next();
					if( !sourceLocation.equalsIgnoreCase( targetLocation ) )
					{
						transportData = getTransportVector( sourceLocation, targetLocation, transportDataVector );
						transportDataList.add( transportData );
					}
				}
        	}
        }
        return transportDataList;
    }

    /**
     * @param sourceLocation
     * @param targetLocation
     * @param transportDataVector
     * @return
     * This method checks wethere this source and destination have any data already saved
     * else returns default values
     */
    private Vector getTransportVector( String sourceLocation, String targetLocation, Vector transportDataVector )
    {
        Vector transportData 	= new Vector();
        Iterator locationListIt = null;
        Vector location			= null;
        String tempSource		= null;
        String tempTarget		= null;
        boolean flagDataExists	= false;

		transportData.add( sourceLocation );
		transportData.add( targetLocation );

		if( transportDataVector != null && transportDataVector.isEmpty() == false )
		{
			locationListIt = transportDataVector.iterator();

	        while( locationListIt.hasNext() )
	        {
				location = (Vector)locationListIt.next();
				if( location.size() > 2 )
				{
					if( ( (String)location.get(0)).equalsIgnoreCase( sourceLocation ) )
					{
						if( ( (String)location.get(1)).equalsIgnoreCase( targetLocation ) )
						{
							flagDataExists = true;
							break;
						}
					}
				}
	        }

	        if( flagDataExists )
	        {
				transportData.add( location.get( 2 ) );
				transportData.add( location.get( 3 ) );
				transportData.add( location.get( 4 ) );
				transportData.add( location.get( 5 ) );
	        }
	        else
	        {
				transportData.add( "0" );
				transportData.add( "0" );
				transportData.add( "0" );
				transportData.add( "0" );
	        }
		}
		else
		{
			transportData.add( "0" );
			transportData.add( "0" );
			transportData.add( "0" );
			transportData.add( "0" );
		}
        return transportData;
    }

    /**
     * @param vendorString
     * @return @vector
     * This method returns the Vendor Locations as vector
     */
    private Vector getVendorsLocationVector( String vendorString )
    {
        Vector vendorLocations 	= null;
		ArrayList tempList 		= graph.getWorkflowManager().parseString( vendorString , '#' );
		Iterator it 			= tempList.iterator();

		while( it.hasNext() )
		{
			ArrayList vendorDetail  = graph.getWorkflowManager().parseString((String)it.next(),';');
			if( vendorLocations == null )
			{
				vendorLocations = new Vector();
			}

			if( vendorDetail.size() > 1 )
			{
				vendorLocations.add( vendorDetail.get( 2 ) );
			}
		}
        return vendorLocations;
    }

	/* Added by neelima */
	private Vector getTransportActivityData( String transportLocations )
	{
		Vector dataList			= new Vector();
		Vector data 			= null;
		ArrayList locationList 	= graph.getWorkflowManager().parseString( transportLocations, '#' );
		Iterator it 			= locationList.iterator();

		while ( it.hasNext() )
		{
			String temp 			= (String)it.next();
			ArrayList locationData 	= graph.getWorkflowManager().parseString(temp, ';');
			Iterator locationIt		= locationData.iterator();
			// IF there is any data
			if( locationIt.hasNext() )
			{
				data = new Vector();
				while ( locationIt.hasNext() )
				{
					data.add( (String)locationIt.next() );
				}
				dataList.add( data );
			}
		}
		return dataList;
	}

    private void getDefaultVendorLocations()
    {
		URL url;								// URL to connect.
		URLConnection con 	= null;				// Connection Object to connect to URL.
		String str 			= "vendors";		// This is the key specifying the DATA required.
		ObjectOutputStream outStream 	= null; // Byte Stream to write into
		ObjectInputStream inputToApplet = null;	// Byte Stream to read from

		try
		{
			// Connect to com.scalar.chiptrack.operations.process.WorkFlowAction
			// The servlet used to fetch data
			url = new URL( graph.editor.getContextURL()+ "/WorkflowServlet");
			// Open the Connection to the URL
			con = url.openConnection();

			if ( !con.getDoOutput() )
			{
				con.setDoOutput( true );
			}
			con.setDoInput( true );
			con.setUseCaches ( false );
			con.setDefaultUseCaches ( false );
			con.setAllowUserInteraction( true );
			// Set the Content length to the length of data u supose to write to Connection
			con.setRequestProperty ( "CONTENT_LENGTH", "" + str.length() );
			con.setRequestProperty ( "Content-Type", "application/octet-stream" );
			// Connect to the URL
			con.connect();
			// Get the ObjectOutputStream send information to servlet
			outStream = new ObjectOutputStream( con.getOutputStream() );
			// Write the required information to the ObjectOutputStream.
			outStream.writeObject( str );
			outStream.flush();
			outStream.close();

			// Fetch the ObjectInputStream from the connection.
			inputToApplet = new ObjectInputStream( con.getInputStream() );
			try
			{
				// Read the information Fetched from the Servlet
				vendorLocationsMap = (HashMap) inputToApplet.readObject();
			}
			catch ( ClassNotFoundException e2 )
			{
				e2.printStackTrace();
			}
			// Close the InputStream.
			inputToApplet.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
        return;
    }

    private void getProcessParameters()
    {
		URL url;
		URLConnection con 	= null;
		String str 			= "parameters";
		ObjectOutputStream outStream;

		try
		{
			url = new URL( graph.editor.getContextURL()+ "/WorkflowServlet");
			con = url.openConnection();

			if ( !con.getDoOutput() )
			{
				con.setDoOutput( true );
			}
			con.setDoInput( true );
			con.setUseCaches ( false );
			con.setDefaultUseCaches ( false );
			con.setAllowUserInteraction( true );
			con.setRequestProperty ( "CONTENT_LENGTH", "" + str.length() );
			con.setRequestProperty ( "Content-Type", "application/octet-stream" );
			con.connect();

			outStream = new ObjectOutputStream( con.getOutputStream() );
			outStream.writeObject( str );
			outStream.flush();
			outStream.close();

			ObjectInputStream inputToApplet = null;
			inputToApplet = new ObjectInputStream( con.getInputStream() );
			try
			{
				processParametersMap = (HashMap) inputToApplet.readObject();
			}
			catch ( ClassNotFoundException e2 )
			{
				e2.printStackTrace();
			}
			inputToApplet.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return;
    }

    private void getPackageTypes()
    {
		URL url;
		URLConnection con 	= null;
		String str 			= "packageTypes";
		ObjectOutputStream outStream;

		try
		{
			url = new URL( graph.editor.getContextURL()+ "/WorkflowServlet");
			con = url.openConnection();

			if ( !con.getDoOutput() )
			{
				con.setDoOutput( true );
			}
			con.setDoInput( true );
			con.setUseCaches ( false );
			con.setDefaultUseCaches ( false );
			con.setAllowUserInteraction( true );
			con.setRequestProperty ( "CONTENT_LENGTH", "" + str.length() );
			con.setRequestProperty ( "Content-Type", "application/octet-stream" );
			con.connect();

			outStream = new ObjectOutputStream( con.getOutputStream() );
			outStream.writeObject( str );
			outStream.flush();
			outStream.close();

			ObjectInputStream inputToApplet = null;
			inputToApplet = new ObjectInputStream( con.getInputStream() );
			try
			{
				package_types = (Vector) inputToApplet.readObject();
			}
			catch ( ClassNotFoundException e2 )
			{
				e2.printStackTrace();
			}
			inputToApplet.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return;
    }

    private void getComboMap()
    {
		URL url;
		URLConnection con 	= null;
		String str 			= "comboMap" + baseProcessType;
		ObjectOutputStream outStream;

		try
		{
			url = new URL( graph.editor.getContextURL()+ "/WorkflowServlet");
			con = url.openConnection();

			if ( !con.getDoOutput() )
			{
				con.setDoOutput( true );
			}
			con.setDoInput( true );
			con.setUseCaches ( false );
			con.setDefaultUseCaches ( false );
			con.setAllowUserInteraction( true );
			con.setRequestProperty ( "CONTENT_LENGTH", "" + str.length() );
			con.setRequestProperty ( "Content-Type", "application/octet-stream" );
			con.connect();

			outStream = new ObjectOutputStream( con.getOutputStream() );
			outStream.writeObject( str );
			outStream.flush();
			outStream.close();

			ObjectInputStream inputToApplet = null;
			inputToApplet = new ObjectInputStream( con.getInputStream() );
			try
			{
				comboMap = (HashMap) inputToApplet.readObject();
			}
			catch ( ClassNotFoundException e2 )
			{
				e2.printStackTrace();
			}
			inputToApplet.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return;
    }

    private Component getVendorPanel()
    {
        vendorPanel = new JPanel();
		vendorPanel.setLayout( new BoxLayout( vendorPanel,  BoxLayout.X_AXIS ) );
		vendorPanel.setBorder( BorderFactory.createCompoundBorder(
								BorderFactory.createTitledBorder( "Vendor Location Information" ),
								BorderFactory.createEmptyBorder( 1, 1, 1, 1 ) ) );

		scrollPane = new JScrollPane( getVendorTable() );
		vendorPanel.add( scrollPane );
        return vendorPanel;
    }

    private JTable getVendorTable()
    {
		vendorTable =  new JTable( vendorTableModel , new CustomTableColumnModel() , new DefaultListSelectionModel() );
		vendorTable.setDefaultRenderer( Object.class, customTableCellRenderer );

		if( ( attributes.containsKey( "processStepId" ) && attributes.get( "processStepId" ) != null && ( (String)attributes.get( "processStepId" ) ).length() > 1 ) || ( attributes.containsKey( "vendors" ) && attributes.get( "vendors" ) != null ) )
		{
			setVendorTable( baseProcessType );

			Vector vendors 	= getVendorsVector( (String)attributes.get( "vendors" ) );
			vendors 		= checkForNewVendors( vendors );
			Iterator it 	= vendors.iterator();

			vendorTableModel.setColumnCount( vendorTable.getColumnCount() );
			vendorTableModel.setDataVector( vendors, getColumnIdentifiers( vendorTable ) );
			vendorTable.createDefaultColumnsFromModel();

            Enumeration enums = vendorTable.getColumnModel().getColumns();
            TableColumn tableColumn;

	        while (	enums.hasMoreElements() )
	        {
                tableColumn = (TableColumn)enums.nextElement();

	            tableColumn.setHeaderRenderer( renderer );

                if( "Location".equalsIgnoreCase( ( tableColumn.getHeaderValue().toString() ).trim() ) )
                {
                    tableColumn.setPreferredWidth(150);
                }
                else if ( "Select".equalsIgnoreCase( ( tableColumn.getHeaderValue().toString() ).trim() ) )
                {
                    tableColumn.setPreferredWidth(50);
                }
                else if ( "Priority".equalsIgnoreCase( ( tableColumn.getHeaderValue().toString() ).trim() ) )
                {
                    tableColumn.setPreferredWidth(50);
                }
                else if ( ( ( tableColumn.getHeaderValue().toString() ).trim() ).startsWith( "Split" ) )
                {
                    tableColumn.setPreferredWidth(40);
                }
                else if ( ( ( tableColumn.getHeaderValue().toString() ).trim() ).startsWith( "Capacity" ) )
                {
                    tableColumn.setPreferredWidth(60);
                }
	        }
            vendorTable.invalidate();
            vendorTable.validate();
            vendorTable.repaint();
			vendorTable.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
			vendorTable.setDragEnabled( false );
		}

		vendorTable.getSelectionModel().addListSelectionListener( new ListSelectionListener(){
		protected TableColumn col;
		public void valueChanged(ListSelectionEvent e)
		{
			if( vendorTable.getSelectedColumn() > 0)
			{
				vendorTable.removeEditor();
				col = vendorTable.getColumnModel().getColumn( vendorTable.getSelectedColumn() );
				col.setCellEditor( new VendorTableCellEditor() );
			}
		}});
		vendorTable.setPreferredScrollableViewportSize( new Dimension(620, 60) );
		return vendorTable;
    }

	/*	This method checks for any new vendors added for the Process
	 * 	And Any vendor removed for the process.
	 *  Adds the new Vendor to Vector If Added and Removes from
	 *  the vector if the Vendor is removed.
	 */
	private Vector checkForNewVendors( Vector vendors )
	{
		if( vendorLocationsMap.containsKey( baseProcessType ) )
		{
			ArrayList latestVendorLocations = (ArrayList)vendorLocationsMap.get( baseProcessType );
			Vector vendorData ;
			ArrayList presentVendorLocations = new ArrayList();
			if( latestVendorLocations != null && latestVendorLocations.size() > 0 )
			{
				Iterator it = vendors.iterator();
				while( it.hasNext() )
				{
					vendorData = (Vector) it.next();                    
					presentVendorLocations.add( ( ( String )vendorData.get( 2 ) ).substring( 0, ( ( String )vendorData.get( 2 ) ).indexOf( '/', 0) ) );
				}
                //Commented by KumaraSwamy on August 31st, 2004.
				/*it = latestVendorLocations.iterator();

				while ( it.hasNext() )
				{
					String vendor 	= (String)it.next();
					String temp 	= ( vendor ).substring( 0, ( vendor ).indexOf( '/', 0) );
					//System.out.println( "Latest Vendor Name " + temp );
					//String temp = (String)it.next();
					if( !presentVendorLocations.contains( temp ) )
					{
						vendors.add( getDefaultValues( type , vendor ) );
					}
					else
					{
						updateVendorLocation( vendors, vendor );
					}
				}*/
              //Added by KumaraSwamy on August 31st, 2004.
              for( int count = ( latestVendorLocations.size()-1 ) ; count >= 0; count-- )
              {
                   String vendor = (String)latestVendorLocations.get( count ) ;
                   String temp 	= ( vendor ).substring( 0, ( vendor ).indexOf( '/', 0) );
                   if( !presentVendorLocations.contains( temp ) )
					{
						vendors.add( getDefaultValues( type , vendor ) );
					}
					else
					{
						updateVendorLocation( vendors, vendor );
					}
                }

				// this part is added to remove all the vendors which are deleted
				it = presentVendorLocations.iterator();

				while ( it.hasNext() )
				{
					String temp = (String)it.next();
					if( !latestVendorLocations.contains(temp) )
					{
						vendors.remove( getDefaultValues( type , temp ) );
					}
				}
			}
		}
		return vendors;
	}

    /**
     * @param vendors
     * @param vendorLocation
     */
    private void updateVendorLocation( Vector vendors, String vendorLocation )
    {
        String vendorName = ( vendorLocation ).substring( 0, ( vendorLocation ).indexOf( '/', 0) );
        String location	  = ( vendorLocation ).substring( ( vendorLocation ).indexOf( '/', 0) );
        Iterator it = vendors.iterator();
		Vector vendorData = null;

		while( it.hasNext() )
		{
			String temp = null;
			vendorData = (Vector) it.next();
			temp = ( ( String )vendorData.get( 2 ) ).substring( 0, ( ( String )vendorData.get( 2 ) ).indexOf( '/', 0) );
			if( temp.equalsIgnoreCase( vendorName ) )
			{
				vendorData.set( 2, vendorLocation );
			}
		}
    }

    private Vector getVendorsVector( String str )
    {
    	Vector vendors 		= new Vector();
    	Vector vendorData 	= null;
		ArrayList tempList 	= graph.getWorkflowManager().parseString( str , '#' );
		Iterator it 		= tempList.iterator();

		while( it.hasNext() )
		{
			ArrayList vendorDetail  = graph.getWorkflowManager().parseString((String)it.next(),';');
			Iterator vendorIt = vendorDetail.iterator();
			vendorData = new Vector();
			int i = 1;
			while( vendorIt.hasNext() )
			{
				if( i == 1 )
				{
					String tmp = (String)vendorIt.next();
					vendorData.add( new Boolean(tmp) );
				}
				else
				{
					vendorData.add( vendorIt.next() );
				}
				i++;
			}
			if( vendorData.size() > 1)
				vendors.add( vendorData );
		}
        return vendors;
    }

    private Component getCommentPanel()
    {
		commentPanel = new JPanel();

		commentPanel.setLayout( new BoxLayout( commentPanel, BoxLayout.X_AXIS ) );

		if( baseProcessType != null && baseProcessType.equalsIgnoreCase( "Finished Goods" ) )
		{
            commentPanel.setBorder( BorderFactory.createCompoundBorder(
                            BorderFactory.createTitledBorder("Description"),
                            BorderFactory.createEmptyBorder( 1, 1, 1, 1 ) ) );
		}
       else
		{
			commentPanel.setBorder( BorderFactory.createCompoundBorder(
							BorderFactory.createTitledBorder("Comments"),
							BorderFactory.createEmptyBorder( 1, 1, 1, 1 ) ) );
		}

		String commentsText = "";
		if( attributes.get("comments") != null )
		{
			commentsText = (String)attributes.get( "comments" );
		}
		comments = new JTextArea( commentsText , 3 , 27 ) ;
		comments.setLineWrap( true );
		JScrollPane scrollPane = new JScrollPane( comments );
		commentPanel.add( scrollPane );
		commentPanel.add( Box.createRigidArea( new Dimension( 3, 0 ) ) );
		commentPanel.add( Box.createGlue() );
		return commentPanel;
    }

    private Component getDupPartNumberPanel()
    {
    	JPanel middlePanel 	= new JPanel();
		JPanel panel 		= new JPanel();

		panel.setLayout( new BoxLayout( panel, BoxLayout.X_AXIS ) );

		panel.setBorder( BorderFactory.createCompoundBorder(
						 BorderFactory.createTitledBorder( "Equivalent Part Numbers" ),
						 BorderFactory.createEmptyBorder( 2, 2, 2, 2 ) ) );

		JScrollPane leftScrollPane = new JScrollPane( getPartNumberTable() );

		partNumberTable.getSelectionModel().addListSelectionListener( new ListSelectionListener(){
			protected TableColumn col;
			public void valueChanged( ListSelectionEvent e )
			{
                if ( partNumberTable.getSelectedColumn() > 0 )
                {
                    partNumberTable.removeEditor();
                    col = partNumberTable.getColumnModel().getColumn( partNumberTable.getSelectedColumn() );
                    col.setCellEditor( new MyTableCellEditor() );
                }
			} } );


		JPanel rightPanel = new JPanel();
		rightPanel.setLayout( new BoxLayout(rightPanel, BoxLayout.Y_AXIS) );
		addButton 		= new JButton( "Add" );
		deleteButton 	= new JButton( "Delete" );
		addButton.setActionCommand( "AddPartnumber" );
		deleteButton.setActionCommand( "DeletePartnumber" );

		addButton.addActionListener( handler );
		rightPanel.add( addButton );

		rightPanel.add( Box.createRigidArea( new Dimension( 5, 0 ) ) );
		deleteButton.addActionListener( handler );
		rightPanel.add( deleteButton );

		rightPanel.add( Box.createGlue() );
		panel.add( leftScrollPane );
		panel.add( Box.createRigidArea( new Dimension( 5, 0 ) ) );
		panel.add( rightPanel );
		middlePanel.add( panel );
		middlePanel.add( getCommentPanel() );
		return middlePanel;
    }

    private JTable getPartNumberTable()
    {
		Vector columnNames 	= new Vector();
		Vector data 		= new Vector();

		columnNames.add("Part Number");

		String dupPartNumbers = (String)attributes.get("dupPartNumbers");
		if( dupPartNumbers != null && dupPartNumbers.length() > 1 )
		{
			Iterator it = graph.getWorkflowManager().parseString( dupPartNumbers, ';' ).iterator();
			while( it.hasNext() )
			{
				String temp = (String) it.next();
				if( temp != null && temp.length() > 0 )
				{
					Vector tempVector = new Vector();
					tempVector.add( temp );
					data.add( tempVector );
				}
			}
		}
		partNumberTable = new JTable( data, columnNames );
		partNumberTable.setPreferredScrollableViewportSize(new Dimension(220, 30));
		return partNumberTable;
    }

    public JTable getTable(){

		Vector columnNames = new Vector();
		Vector data = new Vector();

		columnNames.add("Parameter");
		columnNames.add("units");
		columnNames.add("Value");

		String parameters = (String)attributes.get("parameters");

        if( parameters != null && parameters.length() > 1 )
		{
			Iterator it = graph.getWorkflowManager().parseString(parameters, ';').iterator();
			while(it.hasNext())
			{
				ArrayList tempList = graph.getWorkflowManager().parseString((String)it.next(), '=');
				if(!tempList.isEmpty() && tempList.size() > 1)
				{
					Vector tempVector = new Vector();
					if( tempList.size() == 2 )
					{
						tempVector.add(tempList.get(0));
						tempVector.add("");
						tempVector.add(tempList.get(1));
					}
					if( tempList.size() == 3 )
					{
                        tempVector.add(tempList.get(0));
						tempVector.add(tempList.get(1));
						tempVector.add(tempList.get(2));
					}
					data.add(tempVector);
				}
			}
            getNewDefaultParameters( data, type );
		}

		//table = new JTable(data, columnNames);
		table = new JTableX( parameterTableModel );
		//table.setModel( parameterTableModel );
		table.setColumnModel( new CustomTableColumnModel() );
		table.setDefaultRenderer( Object.class, customTableCellRenderer );

        RowEditorModel rm = new RowEditorModel();
        table.setRowEditorModel(rm);
        parameterTableModel.setDataVector( data, columnNames );
        /*JComboBox cb = new JComboBox(package_types);
        DefaultCellEditor ed = new DefaultCellEditor(cb);
        ed = new DefaultCellEditor(cb);

        int packageIdRowNo = -1;
        if ( package_types != null && package_types.size() != 0 && data != null && !data.isEmpty() )
        {
            for( int t = 0; t < data.size(); t++ )
            {
                Vector vector = (Vector)data.get(t);
                if ( ((String)vector.get(0)).equalsIgnoreCase( "Package ID") )
                {
                    packageIdRowNo = t;
                    break;
                }
            }
        }*/

		//parameterTableModel.setDataVector( data, columnNames );
        /*if ( packageIdRowNo != -1 )
        {
            rm.addEditorForRow(packageIdRowNo, 2, ed);
        }*/
        //START--TO SET THE COMBOBOX FOR THE SPECIFIED PARAMETERS--------
        JComboBox cb = null;
        DefaultCellEditor ed = null;
        if ( data != null && !data.isEmpty() && comboMap != null )
        {
            for( int t = 0; t < data.size(); t++ )
            {
                Vector vector = (Vector)data.get(t);
                String parameterName = ( String )vector.get( 0 );
                if ( comboMap.containsKey( parameterName ) )
                {
                    Vector comboValues = ( Vector ) comboMap.get ( parameterName );
                    if ( comboValues != null && comboValues.size() != 0 )
                    {
                        cb = new JComboBox ( comboValues );
                        ed = new DefaultCellEditor( cb );
                        rm.addEditorForRow( t, 2, ed );
                    }
                }
            }
        }
        //END----------
		Enumeration enums = table.getColumnModel().getColumns();
		int i=0;
		while ( enums.hasMoreElements() )
		{
			TableColumn tc = (TableColumn)enums.nextElement();
			if( i==0 )
				tc.setPreferredWidth(100);
			else if ( i==1 )
				tc.setPreferredWidth(10);
			else
				tc.setPreferredWidth(100);
			i++;
		}
		table.setPreferredScrollableViewportSize(new Dimension(220, 40));
        table.addKeyListener(keyHandler);
		table.invalidate();
		table.validate();
		table.repaint();
		return table;
	}

	public JPanel getParameterPanel(){

		JPanel panel = new JPanel();

		panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

		panel.setBorder(BorderFactory.createCompoundBorder(
						BorderFactory.createTitledBorder("Parameters"),
						BorderFactory.createEmptyBorder(1, 1, 1, 1)));

		JScrollPane leftScrollPane = new JScrollPane( getTable() );

		table.getSelectionModel().addListSelectionListener( new ListSelectionListener(){
			protected TableColumn col;
            public void valueChanged(ListSelectionEvent e)
            {
                if ( table.getSelectedColumn() > 0 )
                {
            	    table.removeEditor();
                    col = table.getColumnModel().getColumn( table.getSelectedColumn() );
                    col.setCellEditor(new MyTableCellEditor());
                }
            }});

		//table.setModel( parameterTableModel );
		JPanel rightPanel = new JPanel();
		rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
		addButton = new JButton("Add");
		deleteButton = new JButton("Delete");

		addButton.setActionCommand("Add");
		addButton.addActionListener(handler);
		rightPanel.add(addButton);

		rightPanel.add( Box.createRigidArea( new Dimension(5, 0) ) );
		deleteButton.setActionCommand( "Delete" );
		deleteButton.addActionListener( handler );
		rightPanel.add( deleteButton );

		rightPanel.add( Box.createGlue() );
		panel.add( leftScrollPane );
		panel.add( Box.createRigidArea( new Dimension(5, 0) ) );
		panel.add( rightPanel );

		return panel;
	}

    public JPanel getBomPartsPanel(){

        JPanel panel = null;
        Vector data = getBomParts();
        if( data != null && !data.isEmpty())
        {
            panel = new JPanel();
            panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
            panel.setBorder(BorderFactory.createCompoundBorder(
                            BorderFactory.createTitledBorder("BOM Parts"),
                            BorderFactory.createEmptyBorder(1, 1, 1, 1)));
            JScrollPane leftScrollPane = new JScrollPane( getBomPartsTable( data) );
            panel.add( leftScrollPane );
        }
        return panel;
    }


    public JTable getBomPartsTable( Vector data){

		Vector columnNames = new Vector();

		columnNames.add("Bom Part Number");
		columnNames.add("Qty Req/Unit");
		bomPartsTable = new JTable( bomPartsTableModel );
        DefaultTableModel dm = (DefaultTableModel)bomPartsTable .getModel();
		bomPartsTable.setDefaultRenderer( Object.class, customTableCellRenderer );
		dm.setDataVector( data, columnNames );
		bomPartsTable .setPreferredScrollableViewportSize(new Dimension(220, 40));
		bomPartsTable .invalidate();
		bomPartsTable .validate();
		bomPartsTable .repaint();
		return bomPartsTable;
	}

    private Vector getBomParts()
    {
		URL url;
		URLConnection con 	= null;
		String str 			= "BomParts";
		ObjectOutputStream outStream;
        Vector bomPartsVector = null;

		try
		{
			url = new URL( graph.editor.getContextURL()+ "/WorkflowServlet");
			con = url.openConnection();

			if ( !con.getDoOutput() )
			{
				con.setDoOutput( true );
			}
			con.setDoInput( true );
			con.setUseCaches ( false );
			con.setDefaultUseCaches ( false );
			con.setAllowUserInteraction( true );
			con.setRequestProperty ( "CONTENT_LENGTH", "" + str.length() );
			con.setRequestProperty ( "Content-Type", "application/octet-stream" );
			con.connect();

			outStream = new ObjectOutputStream( con.getOutputStream() );
            String processStepId = (String) attributes.get( "processStepId" );
            processStepId = processStepId == null ? "":processStepId.trim();
            str = str+ separator + processStepId;
			outStream.writeObject( str );
			outStream.flush();
			outStream.close();

			ObjectInputStream inputToApplet = null;
			inputToApplet = new ObjectInputStream( con.getInputStream() );
			try
			{
				bomPartsVector = (Vector) inputToApplet.readObject();
			}
			catch ( ClassNotFoundException e2 )
			{
				e2.printStackTrace();
			}
			inputToApplet.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return bomPartsVector;
    }

	public JPanel getTopPanel()
	{
		JPanel panel = new JPanel();

		panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
		panel.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
		panel.add( getPartNumberPanel() );

		/* If Process Step id is not there ..
		 * then the user can change the process type
		 * if the process is already configured he
		 * can not change it
		 */

		if( attributes.get("processStepId") == null || ((String)attributes.get("processStepId")).length() < 1 )
		{
			panel.add( Box.createRigidArea( new Dimension(0, 4) ) );
			panel.add( getProcessTypePanel() );
		}
		return panel;
	}

	public JPanel getPartNumberPanel()
	{
		JPanel panel 	= new JPanel();
		panel.setLayout( new BoxLayout( panel, BoxLayout.Y_AXIS ) );
		panel.setBorder( BorderFactory.createCompoundBorder(
						 BorderFactory.createTitledBorder("Part Number & Name"),
                         BorderFactory.createEmptyBorder( 2, 2, 2, 2 ) ) );
		// Add the Process Name label and text field to Panel
		JPanel topPanel 	= new JPanel();
        JLabel processLabel = new JLabel( "Process Name :" );
		processNameField 	= new JTextField(10);
		processNameField.setEnabled( false );
		topPanel.add( processLabel );
		topPanel.add( processNameField );

		// Add the Part Number label and text field to Panel
		JPanel bottomPanel 		= new JPanel();
		JLabel partNumberLabel 	= new JLabel( "Part Number :" );
		partNumberField 		= new JTextField(15);

        String integrationType = "";
        integrationType = graph.editor.getIntegrationType();

        if( attributes.get("processStepId") == null || ((String)attributes.get("processStepId")).length() < 1 )
		{
                partNumberField.setEnabled( true );
        }
        else{
            if( ( integrationType != null ) && ( "GreatPlains".equalsIgnoreCase( integrationType ) ) )
            {
                partNumberField.setEnabled( false );
            }
        }
		bottomPanel.add(partNumberLabel);
		bottomPanel.add(partNumberField);

		// Add the Bins required checkBox to Panel
		binRequiredPanel 		= new JPanel();
		binsRequiredCheckBox 	= new JCheckBox("Bins Required");
		binsRequiredCheckBox.addActionListener(handler);
		binRequiredPanel.add( binsRequiredCheckBox );

		// Add the Number of Good bins, Rejected Bins Label and TextFields
		binPanel= new JPanel();
		JLabel goodBinLabel 	= new JLabel("No of Good Bins");
		JLabel rejectedBinLabel = new JLabel("No of Rejected Bins");
		goodBinField 			= new JTextField(10);
		rejectedBinField 		= new JTextField(10);
		binPanel.add( goodBinLabel );
		binPanel.add( goodBinField );
		binPanel.add( rejectedBinLabel );
		binPanel.add( rejectedBinField );

		// Add the Is Approved CheckBox for Finished goods to Panel
		approvedProductPanel 	= new JPanel();
		approvedCheckBox 		= new  JCheckBox( "Is a Approved Product");
		approvedProductPanel.add( approvedCheckBox );

        // Add the Is Primary FG CheckBox for Finished goods to Panel
		isPrimaryFGPanel 	= new JPanel();
		isPrimaryFGCheckBox 		= new  JCheckBox( "Is a Primary FG Product");
		isPrimaryFGPanel.add( isPrimaryFGCheckBox );

        // Add the Marketing Part Number Label and Text Field to panel
		mktPanel 				= new JPanel();
		JLabel mktPartNumber 	= new JLabel( Editor.mktgPartTitle+":" );
		mktPartNumberField 		= new JTextField(15);

        if( attributes.get("processStepId") == null || ((String)attributes.get("processStepId")).length() < 1 )
		{
                mktPartNumberField.setEnabled( true );
        }
        else{
            if( ( integrationType != null ) && ( "GreatPlains".equalsIgnoreCase( integrationType ) ) )
            {
                mktPartNumberField.setEnabled( false );
            }
        }
		mktPanel.add( mktPartNumber );
		mktPanel.add( mktPartNumberField );

		if( attributes.get("partnumber") == null )
		{
			partNumberField.setText( graph.getEditor().getName() );
		}
		else
		{
			partNumberField.setText( (String)attributes.get("partnumber") );
		}

		if( type != null )
		{
			//processNameField.setText( (String)attributes.get( "value" ) );
			processNameField.setText( type );
		}

		//if( attributes.get( "processStepId" ) != null && ( ( String )attributes.get( "processStepId" ) ).length() > 0 )
		//{
		//	processNameField.setEditable( false );
		//}

        JPanel partStatusPanel = new JPanel();
        JLabel partStatusLabel = new JLabel( "Part Status :" );
        String partStatuses[] = { "Engg", "Pre Prod", "Prod", "Ramp Down", "Last Buy", "Obsolete" };
        partStatusField = new JComboBox(partStatuses);
        //partStatusCombobox.setSize( new Dimension( 50, 20 ));
        partStatusPanel.add ( partStatusLabel);
        partStatusPanel.add ( partStatusField);
        if( attributes.get("partStatus") == null )
		{
			partStatusField.setSelectedItem( "Prod" );
		}
		else
		{
			partStatusField.setSelectedItem( (String)attributes.get("partStatus") );
		}

        JPanel productGroupPanel = new JPanel();
        JLabel productGroupLabel = new JLabel( "Product Group :" );
        String productGroups[] = { "", "ACCESS", "GATEWAY" };
        productGroupField = new JComboBox(productGroups);
        productGroupPanel.add ( productGroupLabel);
        productGroupPanel.add ( productGroupField);
        if( attributes.get("productGroup") == null )
		{
			productGroupField.setSelectedItem( "" );
		}
		else
		{
			productGroupField.setSelectedItem( (String)attributes.get("productGroup") );
		}
        // Here add all the Panels to main Panel
		panel.add( topPanel );
		panel.add( bottomPanel );
		panel.add( binRequiredPanel );
		panel.add( binPanel );
		panel.add( mktPanel );
        panel.add ( partStatusPanel );
        panel.add ( productGroupPanel );
        panel.add( approvedProductPanel );
        panel.add( isPrimaryFGPanel );

		/*  Here this logic makes all the panels
		 *  Visable and Invisable according to the
		 *  Requirement
		 */
		//if( attributes.get( "Type" ) != null && ( (String)attributes.get( "Type" ) ).equalsIgnoreCase( ProcessTypes.finishedGoods) )
		if( baseProcessType != null && baseProcessType.equalsIgnoreCase( "Finished Goods" ) )
		{
           	if( attributes.containsKey( "mktPartNumber" ) )
			{
				mktPartNumberField.setText( (String)attributes.get( "mktPartNumber" ) );
			}

			if( attributes.containsKey( "isApprovedProduct" ) )
			{
				if( ( (String)attributes.get( "isApprovedProduct" ) ).equalsIgnoreCase( "true" ) )
					approvedCheckBox.getModel().setSelected( true );
				else
					approvedCheckBox.getModel().setSelected( false );
			}
            if( attributes.containsKey( "isPrimaryFGProduct" ) )
			{
				if( ( (String)attributes.get( "isPrimaryFGProduct" ) ).equalsIgnoreCase( "true" ) )
					isPrimaryFGCheckBox.getModel().setSelected( true );
				else
					isPrimaryFGCheckBox.getModel().setSelected( false );
			}
            binPanel.setVisible( false );
			binRequiredPanel.setVisible( false );
		}
		//else if( attributes.get( "Type" ) != null &&  ( attributes.get( "Type" ).equals( "SORT" ) || attributes.get( "Type" ).equals( "TEST" ) ) )
		else if( baseProcessType != null &&  ( baseProcessType.equals( "SORT" ) || baseProcessType.equals( "TEST" ) ) )
		{
			if( attributes.containsKey( "binsRequired" ) )
			{
				if( ( (String)attributes.get( "binsRequired" ) ).equalsIgnoreCase( "true" ) )
				{
					binsRequiredCheckBox.getModel().setSelected( true );

					if( attributes.containsKey( "goodBinNumber" ) )
					{
						goodBinField.setText( (String)attributes.get( "goodBinNumber" ) );
					}
					if( attributes.containsKey( "rejectedBinNumber" ) )
					{
						rejectedBinField.setText( (String)attributes.get( "rejectedBinNumber" ) );
					}
				}
				else
				{
					binsRequiredCheckBox.getModel().setSelected( false );
					binPanel.setVisible( false );
				}
			}
			else
			{
				binsRequiredCheckBox.getModel().setSelected( false );
				binPanel.setVisible( false );
			}

			mktPanel.setVisible( false );
			approvedProductPanel.setVisible( false );
			isPrimaryFGPanel.setVisible( false );
		}
		else
		{
			mktPanel.setVisible( false );
			approvedProductPanel.setVisible( false );
            isPrimaryFGPanel.setVisible( false );
            binPanel.setVisible( false );
			binRequiredPanel.setVisible( false );
		}
		return panel;
	}
	public JPanel getProcessTypePanel()
	{
		JPanel panel = new JPanel();
		//panel.setLayout( new BoxLayout( panel, BoxLayout.Y_AXIS ) );
		panel.setLayout( new FlowLayout() );
		panel.setBorder( BorderFactory.createCompoundBorder(
						BorderFactory.createTitledBorder( "Process Type" ),
						BorderFactory.createEmptyBorder( 1, 1, 1, 1 ) ) );

		availableProcessTypes 	= new JComboBox();
		Iterator it				= processParametersMap.keySet().iterator();
		//String processType 		= (String)attributes.get( "value" );
		String processType 		= type;
		//String[] processes		= new String[ processParametersMap.size() ];
		//int i					= 0;
		availableProcessTypes.setEditable( false );
		availableProcessTypes.setBackground( Color.WHITE );
		availableProcessTypes.addItem( "select process" );

		// This is done to sort the process types
		Object[] arrayKey =  processParametersMap.keySet().toArray();
		java.util.Arrays.sort( arrayKey );

		for( int count = 0; count < arrayKey.length; count++ )
		{
			availableProcessTypes.addItem( (String) arrayKey[ count ] );
		}

		/*while( it.hasNext() )
		{
			availableProcessTypes.addItem( ( String ) it.next() );
		}*/

		if( processType != null )
		{
			availableProcessTypes.setSelectedItem( processType );
		}
		availableProcessTypes.setFont( new Font(null, Font.BOLD ,10 ) );
		availableProcessTypes.addActionListener( handler );

		panel.add( availableProcessTypes );
		return panel;
	}

	public JPanel getBottomPanel()
	{
		JPanel panel 		= new JPanel();
		JButton okButton 	= new JButton("Ok");
		JButton cancelButton= new JButton("Cancel");
		okButton.setActionCommand( "Ok" );
		cancelButton.setActionCommand( "Cancel" );
		okButton.addActionListener( handler );
		cancelButton.addActionListener( handler );
		panel.add( okButton );
		panel.add( cancelButton );

		return panel;
	}

	private class CustomTableColumnModel extends DefaultTableColumnModel
	{
		public void moveColumn(int columnIndex,
							   int newIndex){}
	}

	private class ActionHandler implements ActionListener
	{
		public void actionPerformed( ActionEvent e )
		{
			if( e.getSource() instanceof JButton )
			{
		 		if( e.getActionCommand().equalsIgnoreCase( "Ok" ) )
		 		{
		 			// For Cell
		 			if( !( cell instanceof DefaultEdge ) )
		 			{
                        if( table.isEditing() )
						{
							Component c = table.getEditorComponent();

                            if( c != null )
						    {
						    	String val = "";
						        if( c instanceof JTextField )
						        	val = ( ( JTextField )c ).getText();
                                if ( val != null && val.length() > 0 )
                                {
						            table.getModel().setValueAt ( val, table.getEditingRow(), table.getEditingColumn() );
						            table.removeEditor();
                                }
						    }
						 }

						 if( partNumberTable.isEditing() )
						 {
						 	 Component c = partNumberTable.getEditorComponent();
                             if( c != null )
							 {
							 	 String val = "";
								 if( c instanceof JTextField )
									 val = ( ( JTextField )c ).getText();
                                 if ( val != null )
                                 {
                                    partNumberTable.getModel().setValueAt ( val.trim(), partNumberTable.getEditingRow(), partNumberTable.getEditingColumn() );
								    partNumberTable.removeEditor();
                                 }
							 }
						 }

						 if( vendorTable.isEditing() )
						 {
							 Component c = vendorTable.getEditorComponent();
							 if( c != null )
							 {
								 String val = "";
								 if( c instanceof JTextField )
									 val = ( (JTextField) c ).getText();
                                if ( val != null && val.length() > 0 )
                                {
                                    vendorTable.getModel().setValueAt ( val, vendorTable.getEditingRow(), vendorTable.getEditingColumn() );
                                    vendorTable.removeEditor();
                                }
							 }
						 }

						String msg = chkProcess();
						String partNumbers = "";
						if( msg.length() > 1 )
						{
							JOptionPane.showMessageDialog(frame,msg,"Chiptrac Error",JOptionPane.ERROR_MESSAGE);
						}
						else
						{

                            //triming the leading and trailing spaces in the marketing part number.
                            if( baseProcessType.equalsIgnoreCase( "Finished Goods" ) )
                            {
                                if( mktPartNumberField.getText() != null && mktPartNumberField.getText().length() > 0 )
                                {
                                   mktPartNumberField.setText( mktPartNumberField.getText().trim() );
                                }
                            }

                            //triming the leading and trailing spaces in the part number.
                            if( partNumberField.getText() != null && partNumberField.getText().length() > 0 )
                            {
                               partNumberField.setText( partNumberField.getText().trim() );
                            }

                            partNumbers 	= partNumberField.getText().trim();
							int rowCount 		= partNumberTable.getRowCount();

							if( rowCount > 0 )
							{
								for( int i = 0; i < rowCount; i++ )
								{
									if( partNumberTable.getValueAt(i, 0) != null && ( (String)partNumberTable.getValueAt(i, 0) ).length() > 0 )
									{
										partNumberTable.getModel().setValueAt( ((String)partNumberTable.getValueAt(i, 0)).trim() , i, 0);
                                        partNumbers = partNumbers + "," + ( ( String ) partNumberTable.getValueAt( i, 0 ) );
									}
								}
							}
							msg = chkForDuplicates( ( String ) attributes.get( "processStepId" ), partNumbers, type, 0 );

							// This is required when
							//if( msg.length() < 1 )
							//{
							//	msg = chkUnSavedPartNumbers();
							//}

							String msg1 = "";

							if( msg.length() < 1 )
							{
								if( baseProcessType.equalsIgnoreCase( "Finished Goods" ) )
								{
									if( mktPartNumberField.getText() != null && mktPartNumberField.getText().length() > 0 )
									{
                                        if ( !graph.editor.isDupMktgPartNumberAllowed() )
                                        {
                                            msg1 = chkForDuplicates( ( String ) attributes.get( "processStepId" ), mktPartNumberField.getText(), type, 1 );
                                        }
                                    }
								}
							}

                            if ( msg.length() < 1 && msg1.length() < 1 )
                            {
                                if ( !graph.editor.isDupMktgPartNumberAllowed() )
                                {
                                    msg1 = chkForMarketingPartNumber();
                                }
                            }

							if( msg.length() > 1 )
							{
								JOptionPane.showMessageDialog( frame, "Part Numbers "+ msg + "  already Exists ", "Chiptrac Error", JOptionPane.ERROR_MESSAGE );
							}
							else if( msg1.length() > 1 )
							{
								JOptionPane.showMessageDialog( frame, "Marketing Part Number "+ msg1 + "  already Exists ", "Chiptrac Error", JOptionPane.ERROR_MESSAGE );
							}
							else
							{   //JOptionPane.showMessageDialog( frame, "Part Numbers not"+ msg + "  already Exists ", "Chiptrac Error", JOptionPane.ERROR_MESSAGE );
								updateCellAttributes();

                                Map attributes = cell.getAttributes();
                                String processStepId = (String)attributes.get("processStepId");
                                if ( processStepId != null && processStepId.trim().length() > 0 ) //UPDATING ALREADY SAVED PROCESS
                                {
                                    msg = saveAttributesInDB();
                                    if ( msg.startsWith( "SUCCESS" ) )
                                    {
                                        processStepId = msg.substring( msg.indexOf(':')+1 );
                                        JOptionPane.showMessageDialog(frame,"Process Saved Successfully","Chiptrac Info",JOptionPane.NO_OPTION );
                                        //attributes.put ( "processStepId", processStepId );
                                        GraphConstants.setBackground(attributes, Color.white);
                                        cell.changeAttributes( attributes );
                                        frame.dispose();
                                        editComponent.requestFocus();
                                    }
                                    else
                                    {
                                        JOptionPane.showMessageDialog(frame,msg,"Chiptrac Error",JOptionPane.ERROR_MESSAGE);
                                    }
                                }
                                else
                                {
                                    frame.dispose();
                                    editComponent.requestFocus();
                                }
                            }
						}
		 			}
		 			else  // For Transition
		 			{
						if( transportTable.isEditing() )
						{
							Component c = transportTable.getEditorComponent();
							if( c != null )
							{
								String val = "";
								if( c instanceof JTextField )
									val = ( ( JTextField )c ).getText();
                                if ( val != null && val.length() > 0 )
                                {
								    transportTable.getModel().setValueAt ( val, transportTable.getEditingRow(), transportTable.getEditingColumn() );
								    transportTable.removeEditor();
                                }
							}
						}

                        //Added by KumaraSwamy on 14th July, 2004.
						String errormsg = "";
						errormsg = validateTrasportInformation();
						if( errormsg.length() > 1 )
						{
							JOptionPane.showMessageDialog(frame,errormsg,"Chiptrac Error",JOptionPane.ERROR_MESSAGE);
						}
						else
						{
							// Update the Edge Attributes
							updateEdgeAttributes();
							// Send the focus back to graph
							frame.dispose();
							editComponent.requestFocus();
						}
		 			}
		 		}

		 		if(e.getActionCommand().equalsIgnoreCase("Cancel"))
		 		{
		 			frame.dispose();
		 		}
		 		if(e.getActionCommand().equalsIgnoreCase("Add"))
		 		{
                    if( table.isEditing() )
                    {
                        Component c = table.getEditorComponent();

                        if( c != null )
                        {
                            String val = "";
                            if( c instanceof JTextField )
                                val = ( ( JTextField )c ).getText();
                            if ( val != null && val.length() > 0 )
                            {
                                table.getModel().setValueAt ( val, table.getEditingRow(), table.getEditingColumn() );
                                table.removeEditor();
                            }
                        }
                    }
		 			insertNewTableRow(table);
		 		}
		 		if(e.getActionCommand().equalsIgnoreCase("Delete"))
		 		{
                    if( table.getSelectedRow() >= (ParameterTypes.getDefaultParameters( baseProcessType )).size()  )
						removeTableRow(table);
                     table.removeEditor();
		 		}
				if(e.getActionCommand().equalsIgnoreCase("AddPartnumber"))
				{
                    if( partNumberTable.isEditing() )
                    {
                        Component c = partNumberTable.getEditorComponent();
                        if( c != null )
                        {
                            String val = "";
                            if( c instanceof JTextField )
                                val = ( ( JTextField )c ).getText();
                            if ( val != null && val.length() > 0 )
                            {
                                partNumberTable.getModel().setValueAt ( val, partNumberTable.getEditingRow(), partNumberTable.getEditingColumn() );
                                partNumberTable.removeEditor();
                            }
                        }
                    }
					insertNewTableRow( partNumberTable );
				}
		 		if(e.getActionCommand().equalsIgnoreCase("DeletePartnumber"))
		 		{
					removeTableRow( partNumberTable );
                    partNumberTable.removeEditor();
		 		}
		 	}
		 	if( e.getSource() instanceof JComboBox )
		 	{
				type 			= (String) availableProcessTypes.getSelectedItem();
                try {
				    baseProcessType = ( String )( ( ( HashMap ) processParametersMap.get( type ) ).get( "Base_Process_type" ) ) ;

                    processNameField.setText( type );
                    binsRequiredCheckBox.getModel().setSelected( false );
                    goodBinField.setText( "" );
                    rejectedBinField.setText( "" );
                    mktPartNumberField.setText( "" );
                    approvedCheckBox.getModel().setSelected( false );
                    isPrimaryFGCheckBox.getModel().setSelected( true );

                    reloadParameterTable( type );

                    mktPanel.setVisible( false );
                    approvedProductPanel.setVisible( false );
                    isPrimaryFGPanel.setVisible( false );
                    binPanel.setVisible( false );
                    binRequiredPanel.setVisible( false );

                    DefaultTableModel dtm = (DefaultTableModel)partNumberTable.getModel();
                    while( partNumberTable.getRowCount() > 0 )
                    {
                        dtm.removeRow(0);
                    }
                    partNumberTable.invalidate();
                    partNumberTable.validate();
                    partNumberTable.repaint();
                    partNumberTable.removeEditor();

                    comments.setText("");
                    commentPanel.setBorder( BorderFactory.createCompoundBorder(
                                     BorderFactory.createTitledBorder("Comments"),
                                     BorderFactory.createEmptyBorder( 1, 1, 1, 1 ) ) );
                    if( baseProcessType.equalsIgnoreCase( "Finished Goods" ) )
                    {
                        mktPanel.setVisible( true );
                        approvedProductPanel.setVisible( true );
                        isPrimaryFGPanel.setVisible( true );
                        commentPanel.setBorder( BorderFactory.createCompoundBorder(
                                        BorderFactory.createTitledBorder("Description"),
                                        BorderFactory.createEmptyBorder( 1, 1, 1, 1 ) ) );
                    }
                    else if( baseProcessType.equalsIgnoreCase ( "SORT" ) || baseProcessType.equalsIgnoreCase( "TEST" ) )
                    {
                        binRequiredPanel.setVisible( true );
                        binsRequiredCheckBox.getModel().setSelected( false );
                    }

                    // this is to set the vendor details as of process
                    setVendorTable  ( baseProcessType );
                    setVendorDetails( baseProcessType );
                }
                catch ( NullPointerException npe )
                {
                    /*  NullPointerException will arise, when the "select process" is selected from the Process Type
                        Combo Box. When "select process" is Selected, It's required to reset every Field in the Popup Panel
                    */
                    baseProcessType = null;
                    type = "Process";

                    processNameField.setText( type );
                    binsRequiredCheckBox.getModel().setSelected( false );
                    goodBinField.setText( "" );
                    rejectedBinField.setText( "" );
                    mktPartNumberField.setText( "" );
                    approvedCheckBox.getModel().setSelected( false );
                    isPrimaryFGCheckBox.getModel().setSelected( true );

                    int rowCount 		= table.getRowCount();

                    for ( int i = 0 ; i < rowCount ; i++ )
                    {
                        parameterTableModel.removeRow(0);
                    }

                    table.invalidate();
                    table.validate();
                    table.repaint();

                    mktPanel.setVisible( false );
                    approvedProductPanel.setVisible( false );
                    isPrimaryFGPanel.setVisible( false );
                    binPanel.setVisible( false );
                    binRequiredPanel.setVisible( false );

                    DefaultTableModel dtm = (DefaultTableModel)partNumberTable.getModel();
                    while( partNumberTable.getRowCount() > 0 )
                    {
                        dtm.removeRow(0);
                    }
                    partNumberTable.invalidate();
                    partNumberTable.validate();
                    partNumberTable.repaint();

                    partNumberTable.removeEditor();
                    comments.setText("");

                    while( vendorTableModel.getRowCount() > 0 )
                    {
                            vendorTableModel.removeRow(0);
                    }

                     while( vendorTable.getColumnCount() > 0 )
                     {
                         vendorTable.removeColumn( vendorTable.getColumnModel().getColumn(0));
                     }

                    vendorTable.invalidate();
                    vendorTable.validate();
                    vendorTable.repaint();

                }

                mainPanel.validate();
		 	}
			if( e.getSource() instanceof JCheckBox )
			{
				if( e.getActionCommand().equals( "Bins Required" ) )
				{
					if( binsRequiredCheckBox.isSelected() )
					{
						binPanel.setVisible( true );
					}
					else
					{
						binPanel.setVisible( false );
					}
				}
			}
		}
        // If flag = 0 check the Part numbers else if flag = 1 check MktPartNumber
		private String chkForDuplicates( String processStepId, String partNumber, String processType, int flag )
		{
			URL url;
			URLConnection con 		= null;
			String str 				= null;
			String dupPartNumbers 	= "";
			ObjectOutputStream outStream	= null;
			ObjectInputStream inputToApplet = null;

			if( flag == 0 )
			{
				str = "PARTNUMBER";
			}
			else
			{
				str = "MARKETINGPARTNUMBER";
			}
			try
			{
				url = new URL( graph.editor.getContextURL()+ "/WorkflowServlet");
				con = url.openConnection();

				if ( !con.getDoOutput() )
				{
					con.setDoOutput( true );
				}
				con.setDoInput( true );
				con.setUseCaches ( false );
				con.setDefaultUseCaches ( false );
				con.setAllowUserInteraction( true );
				con.setRequestProperty("CONTENT_LENGTH", "" + str.length());
				con.setRequestProperty ("Content-Type", "application/octet-stream");
				con.connect();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
			try
			{
				if( processStepId == null || processStepId.length() < 1 )
					processStepId = "-1";
				str = str + separator +  processStepId + ";" + partNumber + ";" + processType ;

				outStream = new ObjectOutputStream( con.getOutputStream());
				outStream.writeObject(str);
				outStream.flush();
				outStream.close();

				inputToApplet = new ObjectInputStream(con.getInputStream());
				try
				{
					dupPartNumbers = (String) inputToApplet.readObject();
				}
				catch (ClassNotFoundException e2)
				{
					e2.printStackTrace();
				}
				inputToApplet.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
			return dupPartNumbers;
		}

		/**
         * @return
         */
        private String chkNewProcessPartNumbers( String chkPartNumber )
        {
			String dupPartNumbers 	= "";
			String processType 		= type;
			String existingPartNumbersList 	= "";
			ArrayList partNumbersList		= null;
			ArrayList partNumbers			= null;
			ArrayList chkPartNumbersList	= null;
			String existingPartNumber 		= "";

			if( newPartNumberMap != null && newPartNumberMap.isEmpty() == false && newPartNumberMap.containsKey( type )  )
			{
				existingPartNumbersList = (String) newPartNumberMap.get( type );

				if( existingPartNumber != null && existingPartNumber.length() > 0 )
				{
					partNumbersList	= graph.getWorkflowManager().parseString( existingPartNumbersList , ',' );

					for ( int i = 0; i < partNumbersList.size(); i++  )
					{
						if( chkPartNumbersList.contains( partNumbers.get( i ) ) )
						{
							dupPartNumbers = dupPartNumbers + "," + (String)partNumbers.get( i );
						}
					}
				}
			}

			if( dupPartNumbers.length() < 1 )
			{
				newPartNumberMap.put( type, chkPartNumber );
			}
            return dupPartNumbers;
        }

        


        private String chkProcess()
        {
            String msg = "";
			// Checks wether the Part Number is given
            if( partNumberField.getText()== null || partNumberField.getText().length() < 1 )
            {
            	msg = "Part Number cannot be empty \n"	;
            }
            else if( partNumberField.getText().trim().length() > 50)
            {
                msg = "Part Number cannot be more than 50 Characters \n"	;
            }
            else if ("clipboard".equalsIgnoreCase(partNumberField.getText().trim() ) )
            {
                 msg = "Part Number cannot be  clipboard \n"	;
            }
			//	Checks wether any process is selected
			if( type == null || type.length() < 1 || type.equalsIgnoreCase( "Process" ) )
			{
				msg = msg + "Select any one of the Process Type \n";
			}
			// If it is Finished Goods it checks wether Marketing Part Number is given
			if( mktPanel.isVisible() )
			{
				if( mktPartNumberField.getText()== null || mktPartNumberField.getText().length() < 1 )
				{
					msg = msg + "Mkt Part number can not be empty \n";
				}
			}

			// Check for duplicate part numbers in Equivalent Part numbers
			if ( msg.length() < 1 )
			{
				msg = chkDupPartNo();
			}
			// Validate the parameter Table values
            if ( msg.length() < 1 )
			{
				msg = validateParameters();
			}
			// Validate the Vendor table values
			if( msg.length() < 1 )
			{
				msg = validateVendors();
			}
            //Validate the Good and Rejected Bins
            if( msg.length() < 1 )
			{
				msg = validateGoodAndRejectedBins();
			}

			return msg;
        }

     	// Check the units of parameters
		private String validateParameters()
		{
			StringBuffer error 	= new StringBuffer( "" );
			String key		 	= "";
			String parameters	= getAllParameters();
            String[] dups = getDuplicateParameters(parameters);
            if ( dups != null && dups.length > 0 )
            {
                error.append( "Please delete the following Duplicated Parameters: ");
                for ( int i=0 ; i < dups.length; i++ )
                {
                    error.append ( i==0 ? dups[i] : (", "+dups[i]) );
                }
                error.append ( "\n" );
            }
            StringTokenizer sToken = new StringTokenizer( parameters, ";" );
            while ( sToken.hasMoreTokens() )
			{
				String str = sToken.nextToken();
				if ( ( key = chkUnits( str ) ).length() > 1 )
				{
                    if( chkInch( str ).equals("inch^2") )
                    {
                        error.append("'"+key+"' Value should be inbetween 0 and 9999.9999 only \n");
                    }
                    else if(  key.equalsIgnoreCase("Gross Die/Wafer") )
                    {
					    error.append( "'"+key+"' Value can not be empty, should be Valid Integer and value should be from 1 to 99999 \n");
                    }
                    else
                    {
					    error.append( " Enter Valid Value for the Parameter '" + key + "' \n");
                    }
				}
			}
			return error.toString();
		}
        private String[] getDuplicateParameters( String parameters )
        {
            StringTokenizer parametersToken = new StringTokenizer( parameters, ";" );
            Set duplicates = new HashSet();
            Map map = new HashMap();
            while ( parametersToken.hasMoreTokens() )
            {
                String parameter = parametersToken.nextToken();
                StringTokenizer sToken = new StringTokenizer( parameter, "=" );
                String key = sToken.nextToken();
                if ( key != null )
                {
                    key = key.trim().toUpperCase();
                    if ( map.put(key,"") != null )
                    {
                        duplicates.add ( key );
                    }
                }
            }
            String dups[] = new String[duplicates.size()];
            duplicates.toArray(dups);
            return dups;
        }
        // Check the values of Vendor table and atleast one vendor should be selected
		private String validateVendors()
		{
			String vendorData 	= getVendorData();
			StringBuffer error 	= new StringBuffer( "" );
			ArrayList vendors	= graph.getWorkflowManager().parseString( vendorData, '#' );

			// validate Each Vendor Selected
			if( vendors != null && vendors.isEmpty() == false )
			{
				// Check if atleast one Vendor is Selected
				if ( chkVendorSelected( vendors ) )
				{
					// If atleast one vendor is selected
					for( int i = 0; i < vendors.size(); i++ )
					{
						error.append( validateVendorData( (String)vendors.get( i ) ) );
					}
				}
				else
				{
					error.append( "Atleast one Vendor needs to be selected \n" );
				}
			}
			else
			{
				error.append( "Atleast one Vendor needs to be selected \n" );
			}

			return error.toString();
		}

		/**
         * @param vendors
         */
        private boolean chkVendorSelected( ArrayList vendors )
        {
            boolean flag 		= false;
            String vendorData 	= "";

			if ( vendors != null && vendors.isEmpty() == false )
			{
				for( int i = 0; i < vendors.size(); i++ )
				{
					vendorData 		 = ( String ) vendors.get( i );
					ArrayList vendor = graph.workflowManager.parseString( vendorData, ';' );

					if( vendor != null && vendor.isEmpty() == false && ( (String) vendor.get( 0 ) ).equalsIgnoreCase( "true" ) )
					{
						flag = true;
						break;
					}
				}
			}
            return flag;
        }

        // validate Parameters
		private String validateVendorData( String vendor )
		{
			StringBuffer error 	= new StringBuffer("");
			ArrayList vendorData= graph.getWorkflowManager().parseString( vendor, ';' );
			String colName 		=  "";
			boolean status 		= true;

			if ( vendorData != null && vendorData.isEmpty() == false )
			{
				for ( int i = 0; i < vendorData.size(); i++ )
				{
					switch ( i )
					{
						case 0:		//Select
							break;
						case 1:		// Priority
							status  = chkUnit( "units", (String)vendorData.get( 1 ) );
							colName = "Priority";
							break;
						case 2:		// Location
							break;
						case 3:		// Split
							status  = chkUnit( "units", (String)vendorData.get( 3 ) );
							colName = "Split";
							break;
						case 4:		// Capacity/Week
							status  = chkUnit( "units", (String)vendorData.get( 4 ) );
							colName = "Capacity/Week";
							break;
						case 5:		// UnitCost/Normal
							status  = chkUnit( "$", (String)vendorData.get( 5 ) );
							colName = "UnitCost/Normal";
							break;
						case 6:		// UnitCost/Express
							status  = chkUnit( "$", (String)vendorData.get( 6 ) );
							colName = "UnitCost/Express";
							break;
						case 7:		// CycleTime/Normal
							status  = chkUnit( "$", (String)vendorData.get( 7 ) );
							colName = "CycleTime/Normal";
							break;
						case 8:		// CycleTime/Express
							status  = chkUnit( "$", (String)vendorData.get( 8 ) );
							colName = "CycleTime/Express";
							break;
						case 9:		// Expected Yeild
							status  = chkUnit( "%", (String)vendorData.get( 9 ) );
							colName = "Expected Yeild";
							break;
					}
					if ( !status )
					{
						error.append( " enter valid value in column "+ colName +" for Location "+ (String)vendorData.get( 2 ) + "\n" );
					}
				}
			}
			return error.toString();
		}

		//Added by KumaraSwamy 0n 14th July, 2004.
		//validate TransportInformation.
		private String validateTrasportInformation()
		{
            StringBuffer error 	= new StringBuffer("");
			String colName 		=  "";
			boolean status = true;

			for (int i = 0; i < transportTable.getModel().getRowCount() ; i++ )
			{
				for (int j = 2; j < transportTable.getModel().getColumnCount() ; j++ )
				{
					if( ( j == 2 ) || ( j == 3 ) )
					{
						status  = chkInteger( (String)transportTable.getModel().getValueAt(i,j).toString().trim() );
					}
                    else
					{
						status  = chkFloat( (String)transportTable.getModel().getValueAt(i,j).toString().trim() );
					}
					if ( !status )
					{
						switch ( j )
						{
							case 0:
								break;
							case 1:
								break;
							case 2:
								colName = "Normal Shipping Time";
								break;
							case 3:
								colName = "Express Shipping Time";
								break;
							case 4:
								colName = "Normal Shipping Cost";
								break;
							case 5:
								colName = "Express Shipping Cost";
								break;

						}
						error.append( " enter valid value in column "+ colName +" for Source "+ (String)transportTable.getModel().getValueAt(i,0) +" And Destination "+ (String)transportTable.getModel().getValueAt(i,1) + "\n" );
					}
				}
			}

			return error.toString();
		}

        private String validateGoodAndRejectedBins()
		{
            StringBuffer error 	= new StringBuffer("");
		    boolean status1 = true;
			boolean status2 = true;

			if( goodBinField.getText() != null )
			{
			    status1  = chkInteger( goodBinField.getText().trim() );
		    }
            if ( !status1 )
			{
			    error.append( " Enter valid Integer Good Bins \n" );
			}
            if( rejectedBinField.getText() != null )
			{
			    status2  = chkInteger( rejectedBinField.getText().trim() );
		    }
            if ( !status2 )
			{
			    error.append( " Enter valid Integer Rejected Bins \n" );
			}

			return error.toString();
		}


		private String chkUnits( String param )
		{
			StringTokenizer sToken = new StringTokenizer( param, "=" );
			String key = "";
			if ( sToken.countTokens() == 3 )
			{
				key = sToken.nextToken();
				String unit = sToken.nextToken();
				String value = sToken.nextToken();

				boolean status = true;
				if( key.equalsIgnoreCase("Gross Die/Wafer") )
                {
                    status = chkInteger(value);
                    if ( value.trim().length() > 5 || value.trim().equalsIgnoreCase("0") )
                    {
                        status = false;
                    }
                }
                else
                status = chkUnit( unit, value );

                if ( status )
					key = "";
			}
            else// This is for no of Tokens are less three.
            {
                key = sToken.nextToken();
                if( ( key.equalsIgnoreCase("Gross Die/Wafer") ) )
                {
                    //Returnig key value as Gross Die/Wafer.
                }
                else
                    key = "";
            }
			return key;
		}

        private String chkInch( String param )
		{
			StringTokenizer sToken = new StringTokenizer( param, "=" );
			String unit = "";
			if ( sToken.countTokens() == 3 )
			{
				sToken.nextToken();
			    unit = sToken.nextToken();
				String value = sToken.nextToken();
				boolean status = true;
				status = chkUnit( unit, value );
				if ( status )
					unit = "";
			}
			return unit;
		}

		private boolean chkUnit( String unit, String value )
		{
			boolean status = true;

			if ( unit.equals("%") || unit.equals("$") )
			{
				status = chkFloat(value);
			}
			if ( unit.equalsIgnoreCase("units")	|| unit.equalsIgnoreCase("Days") )
			{
				status = chkInteger(value);
			}
            if ( unit.equalsIgnoreCase("inch^2") )
			{
                status = chkFloat(value);
                if( status )
                {
                    int i = 0;
                    int bd = 0;
                    int ad = 0;
                    i = value.indexOf(".");
                    if( i == -1 )
                    {
                        i = 0;
                        value = value + ".00";
                        i = value.indexOf(".");
                    }
                    bd = value.substring( 0, i ).length();
                    if( bd > 4 )
                    {
                        status = false;
                    }
                    ad = value.substring( i+1, value.length() ).length();
                    if( ad > 4 )
                    {
                        status = false;
                    }
                }
            }
			return status;
		}

		private boolean chkInteger( String value )
		{
			boolean flag = true;
            int val;
			if( value.equals("") )
			{
				return true;
			}
			else
			{
				try
				{
					if ( value.indexOf(".") == -1 )
					{
						val = Integer.parseInt( value );
						if ( val < 0 )
						{
							flag = false;
						}
					}
					else
						flag = false;
				}
				catch ( NumberFormatException ne )
				{
					flag = false;
				}
				finally
				{
					
				}
				return flag;
			}
		}

		private boolean chkFloat( String value )
		{
			boolean flag = true;
			int index;
			float value1;
			try
			{
				if ( ( index = value.indexOf(".") ) == -1 )
				{
					value = value + ".00";
				}
				value1 = Float.parseFloat( value );
                if ( value1 < 0 )
                {
                    flag = false;
                }
			}
			catch ( NumberFormatException ne )
			{
				flag = false;
			}
			finally
			{
				
			}
			return flag;
		}

		private String chkDupPartNo()
		{
			String error 	 		= "";
			String partField 		= partNumberField.getText().trim();
            if  ( partField != null )
            {
                partNumberField.setText( partField );
            }
			String dupPartNumbers 	= getDupPartNumbers();
			ArrayList partNumbers 	= graph.getWorkflowManager().parseString( dupPartNumbers, ';' );

			partNumbers.add( partField );

			for ( int k = 0; k < partNumbers.size()-1; k++ )
			{
				for ( int j = k+1; j < partNumbers.size(); j++ )
				{
					if ( ( ( String ) partNumbers.get( k ) ).equalsIgnoreCase( ( String ) partNumbers.get( j ) ) )
					{
						error = "\n  PartNumbers Should not be repeated ";
						break;
					}
				}
			}
			return error;
		}
	} //Action Handler

    private void setVendorDetails( String processType )
    {
        if( vendorLocationsMap != null )
        {
            if( vendorLocationsMap.containsKey( processType ) )
            {
                ArrayList vendorLocations  = ( ArrayList )vendorLocationsMap.get( processType );
                if( vendorLocations != null && vendorLocations.size() > 0 )
                {
                    Iterator it = vendorLocations.iterator();
                    while( vendorTableModel.getRowCount() > 0 )
                    {
                        vendorTableModel.removeRow(0);
                    }

                    vendorTableModel.setColumnCount( vendorTable.getColumnCount() );
                    vendorTableModel.setColumnIdentifiers( getColumnIdentifiers( vendorTable ));

                    while( it.hasNext() )
                    {
                        Vector rowData = getDefaultValues( processType , (String)it.next() );
                        vendorTableModel.insertRow( 0 , rowData );
                    }
                    vendorTable.createDefaultColumnsFromModel();
                }
            }
        }

        Enumeration enums = vendorTable.getColumnModel().getColumns();
        TableColumn tableColumn;
        while (enums.hasMoreElements()) {
            tableColumn = (TableColumn)enums.nextElement();

            tableColumn.setHeaderRenderer(renderer);

            if("Location".equalsIgnoreCase((tableColumn.getHeaderValue().toString()).trim()))
            {
                tableColumn.setPreferredWidth(150);
            }
            else if ("Select".equalsIgnoreCase((tableColumn.getHeaderValue().toString()).trim()))
            {
                tableColumn.setPreferredWidth(50);
            }
            else if ("Priority".equalsIgnoreCase((tableColumn.getHeaderValue().toString()).trim()))
            {
                tableColumn.setPreferredWidth(50);
            }
            else if (((tableColumn.getHeaderValue().toString()).trim()).startsWith("Split"))
            {
                tableColumn.setPreferredWidth(40);
            }
            else if (((tableColumn.getHeaderValue().toString()).trim()).startsWith("Capacity"))
            {
                tableColumn.setPreferredWidth(60);
            }

        }
        vendorTable.invalidate();
        vendorTable.validate();
        vendorTable.repaint();
    }

    /*   The Logic in this works like..
		 * 	 It removes the all the rows present in the Table
		 * 	 It then adds rows one after the other
		 */
	    private void reloadParameterTable( String type )
		{
			//Vector tableData  = ParameterTypes.getDefaultParameters( type );
			// Fetch the Vector containing Vector of Parameter Name, Units , Default Value
            Vector tableData	= ( Vector )( ( HashMap )processParametersMap.get( type ) ).get( "parameters" );
			int rowCount 		= table.getRowCount();
			Iterator it 		= tableData.iterator();
			Enumeration enums 	= table.getColumnModel().getColumns();
			DefaultTableModel dtm 	= (DefaultTableModel)table.getModel();

			for ( int i = 0 ; i < rowCount ; i++ )
			{
				parameterTableModel.removeRow(0);
			}

			while( it.hasNext() )
			{
				parameterTableModel.addRow( (Vector)it.next() );
			}

            RowEditorModel rm = new RowEditorModel();
            table.setRowEditorModel(rm);

            /*JComboBox cb = new JComboBox(package_types);
            DefaultCellEditor ed = new DefaultCellEditor(cb);
            ed = new DefaultCellEditor(cb);

            int packageIdRowNo = -1;
            if ( package_types != null && package_types.size() != 0 && tableData != null && !tableData.isEmpty() )
            {
                for( int t = 0; t < tableData.size(); t++ )
                {
                    Vector vector = (Vector)tableData.get(t);
                   if ( ((String)vector.get(0)).equalsIgnoreCase( "Package ID") )
                    {
                        packageIdRowNo = t;
                        break;
                    }
                }
            }*/

            //parameterTableModel.setDataVector( data, columnNames );
            /*if ( packageIdRowNo != -1 )
            {
                rm.addEditorForRow(packageIdRowNo, 2, ed);
            }*/
            getComboMap();
            JComboBox cb = null;
            DefaultCellEditor ed = null;
            if ( tableData != null && !tableData.isEmpty() && comboMap != null )
            {
                for( int t = 0; t < tableData.size(); t++ )
                {
                    Vector vector = (Vector)tableData.get(t);
                    String parameterName = ( String )vector.get( 0 );
                    if ( comboMap.containsKey( parameterName ) )
                    {
                        Vector comboValues = ( Vector ) comboMap.get ( parameterName );
                        if ( comboValues != null && comboValues.size() != 0 )
                        {
                            cb = new JComboBox ( comboValues );
                            ed = new DefaultCellEditor( cb );
                            rm.addEditorForRow( t, 2, ed );
                        }
                    }
                }
            }

			// set the column widths of the table
			int i = 0;
			while ( enums.hasMoreElements() )
			{
				TableColumn tc = (TableColumn)enums.nextElement();
				if( i == 0 )
					tc.setPreferredWidth( 100 );
				else if ( i == 1 )
					tc.setPreferredWidth( 10 );
				else
					tc.setPreferredWidth( 100 );
				i++;
			}
			table.setPreferredScrollableViewportSize( new Dimension( 220, 40 ) );
			table.invalidate();
			table.validate();
			table.repaint();
			return;
		}

    /*
    This is Handler is to perform the Tab Functionality in Parameter Table properly.
    */
	private class KeyHandler extends KeyAdapter
	{
		public void keyReleased(KeyEvent e)
		{
			if( e.getSource() instanceof JTable )
			{
                if ( e.getKeyCode() == KeyEvent.VK_TAB )
                {
                   table.removeEditor();
                }
            }
        }
    }

	private Vector getDefaultValues( String processType, String loc )
	{
		Vector defaultLocationValues = new Vector();

		defaultLocationValues.add( new Boolean("false") );
		defaultLocationValues.add( "0" );
		defaultLocationValues.add( loc );

		if( !processType.equalsIgnoreCase( "Wafer Store" ) && !processType.equalsIgnoreCase( "Die Bank" ) && !processType.equalsIgnoreCase( "Class Store" ) && !processType.equalsIgnoreCase( "Finished Goods" ))
		{
			defaultLocationValues.add( "0" );
			defaultLocationValues.add( "0" );
			defaultLocationValues.add( "0" );
			defaultLocationValues.add( "0" );
			defaultLocationValues.add( "0" );
			defaultLocationValues.add( "0" );
			defaultLocationValues.add( "0" );
		}
		return defaultLocationValues;
	}

	public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor
	{
		JComponent component = new JTextField();
		JTable table;
		int row ;
		int col;

		public Component getTableCellEditorComponent(JTable table, Object value,
				boolean isSelected, int rowIndex, int vColIndex) {

			if (isSelected)
			{
				this.table  = table;
				row = rowIndex;
				col = vColIndex;
			}
			((JTextField)component).setText((String)value);
			return component;
		}

		public Object getCellEditorValue() {
			return ((JTextField)component).getText();
		}

		public boolean isCellEditable(EventObject anEvent)
		{
 			return true;
		}

		public boolean shouldSelectCell(EventObject anEvent)
		{
			return true;
		}

		public boolean stopCellEditing()
		{
			table.getModel().setValueAt( getCellEditorValue(), row, col);
			return true;
		}

		public void cancelCellEditing(){}
		public void addCellEditorListener(CellEditorListener l){}
		public void removeCellEditorListener(CellEditorListener l){}
	}

	public class VendorTableCellEditor extends AbstractCellEditor implements TableCellEditor
	{
		JComponent component = new JTextField();
		JComponent chkComponent = new JCheckBox();

		JTable table;
		int row ;
		int col;

		public Component getTableCellEditorComponent(JTable table, Object value,
				boolean isSelected, int rowIndex, int vColIndex) {

			if (isSelected)
			{
				this.table  = table;
				row = rowIndex;
				col = vColIndex;
			}

			if( col != 0 )
			{
				((JTextField)component).setText((String)value);
				return component;
			}
			else if( col == 0 )
			{
				((JCheckBox)chkComponent).setSelected(((Boolean)value).booleanValue());
				return chkComponent;
			}
			return null;
		}

		public Object getCellEditorValue() {
			if( col == 0  )
				return ((JCheckBox)chkComponent).getText();
			else
				return ((JTextField)component).getText();
		}

		public boolean isCellEditable(EventObject anEvent)
		{
            return true;
        }

		public boolean shouldSelectCell(EventObject anEvent)
		{
			return true;
		}

		public boolean stopCellEditing()
		{
			table.getModel().setValueAt( getCellEditorValue(), row, col);
			return true;
		}
		public void cancelCellEditing(){}
		public void addCellEditorListener(CellEditorListener l){}
		public void removeCellEditorListener(CellEditorListener l){}
	}

	public class TransportTableCellEditor extends AbstractCellEditor implements TableCellEditor
	{
		JComponent component 	= new JTextField();
		JComponent chkComponent = new JCheckBox();

		JTable table;
		int row ;
		int col;

		public Component getTableCellEditorComponent(JTable table, Object value,
				boolean isSelected, int rowIndex, int vColIndex) {

			if ( isSelected )
			{
				this.table  = table;
				row = rowIndex;
				col = vColIndex;
			}

			((JTextField)component).setText((String)value);
			return component;
		}

		public Object getCellEditorValue()
		{
			return ((JTextField)component).getText();
		}

		public boolean isCellEditable(EventObject anEvent)
		{
			return true;
		}

		public boolean shouldSelectCell(EventObject anEvent)
		{
			return true;
		}

		public boolean stopCellEditing()
		{
			table.getModel().setValueAt( getCellEditorValue(), row, col);
			return true;
		}
		public void cancelCellEditing(){}
		public void addCellEditorListener(CellEditorListener l){}
		public void removeCellEditorListener(CellEditorListener l){}
	}

	public class VendorTableModel extends DefaultTableModel
	{
       public Class getColumnClass(int c)
		{
			Boolean b = new Boolean("false");
			String s = "";
			if( c == 0  )
			{
				return b.getClass();
			}
			else
			{
				return s.getClass();
			}
		}

        public boolean isCellEditable(int row , int col)
        {
            if(col == 0)
            {   /*  Checking Weather Vendor holding any Lots. If so, We should not uncheck the Vendor from Vendor Location Info */
                String cellValue  = (String) this.getValueAt( row, 2 );
                if ( this.getValueAt( row , 0 ).equals( new Boolean("true")) && vendorsWithLots != null && vendorsWithLots.contains( cellValue ) )
                {
                    JOptionPane.showMessageDialog(frame,"Lot Exist for Vendor. You cann't uncheck.","Chiptrac Error",JOptionPane.ERROR_MESSAGE);
                    return false;
                }
                return true;
            }
            else if(col == 2)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
	}

	public class TrasportTableModel extends DefaultTableModel
	{
		public boolean isCellEditable( int row, int col )
		{
			if( col == 0 || col == 1 )
			{
				return false;
			}
			else
			{
				return true;
			}
		}
	}

    public class BOMPartsTableModel extends DefaultTableModel
    {
        public boolean isCellEditable( int row, int col )
        {
                return false;
        }
    }

	public class ParameterTableModel extends DefaultTableModel
	{
		public boolean isCellEditable( int row, int col )
		{
			// Col 2 contains the value which can always be editable
			if( col == 2 )
			{
				return true;
			}

			// If it is a default parameter it should not be deleted from the Table
			// Check wether the value is present in Default Parameters.

			Vector defaultParametersList= null;
			Vector defaultParameter		= null;
			String cellValue 			= (String) this.getValueAt( row, 0 );
			boolean editable			= true;
			if( processParametersMap != null && processParametersMap.containsKey( type ) && ( ( HashMap ) processParametersMap.get( type ) ).containsKey( "parameters" )  )
			{
				defaultParametersList = (Vector)( ( HashMap ) processParametersMap.get( type ) ).get( "parameters" );
			}

			if( defaultParametersList != null && defaultParametersList.isEmpty() == false && cellValue != null )
			{
				for ( int i = 0; i < defaultParametersList.size(); i++ )
				{
					defaultParameter = ( Vector )defaultParametersList.get( i );
					if( defaultParameter != null && defaultParameter.isEmpty() == false )
					{
						if( cellValue.equalsIgnoreCase( (String)defaultParameter.get( 0 ) ) )
						{
							editable = false;
							break;
						}
					}
				}
			}
			else
			{
				editable = true;
			}
			return editable;
		}
	}

	public class MultiLineHeaderRenderer extends JList implements TableCellRenderer
	{
	  	public MultiLineHeaderRenderer()
	  	{
			setOpaque(true);
			setForeground( UIManager.getColor( "TableHeader.foreground" ) );
			setBackground( UIManager.getColor( "TableHeader.background" ) );
			setBorder	 ( UIManager.getBorder( "TableHeader.cellBorder" ) );
			ListCellRenderer renderer = getCellRenderer();
			((JLabel)renderer).setHorizontalAlignment( JLabel.CENTER );
			setCellRenderer( renderer );
	  	}

	  	public Component getTableCellRendererComponent(JTable table, Object value,
					   boolean isSelected, boolean hasFocus, int row, int column)
		{
			setFont( table.getFont() );
			String str = ( value == null ) ? "" : value.toString();
			BufferedReader br = new BufferedReader( new StringReader( str ) );
			String line;
			Vector v = new Vector();
			try
			{
		  		while ( ( line = br.readLine() ) != null )
		  		{
		  			v.addElement( line );
		  		}
			}
			catch ( IOException ex )
			{
		  		ex.printStackTrace();
			}
			setListData( v );

			return this;
		}
	}

	// Modified by neelima on 16-Apr-2004
	public class CustomTableCellRenderer extends JLabel implements TableCellRenderer
	{
		public CustomTableCellRenderer()
		{
			setOpaque(true);
		}

		public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column )
		{
			if ( table.isCellEditable(row,column) )
			{
				this.setBackground(Color.WHITE);
			}
	   		else
	   		{
				this.setBackground( new Color( 233, 233, 233 ) );
	   		}

			this.setFont( new Font( "Default" , Font.PLAIN ,12 ) );
			this.setText( (String) value  );

			return this;
		}
	}

	public void insertNewTableRow(JTable table)
	{
		DefaultTableModel dtm = (DefaultTableModel)table.getModel();
		dtm.addRow(new Vector());
		table.requestFocus();
	}

	public void removeTableRow(JTable table)
	{
		int row = table.getSelectedRow();
		int col = table.getSelectedColumn();
		DefaultTableModel dtm = (DefaultTableModel)table.getModel();
		if(row != -1)
		{
			dtm.removeRow(row);
		}
      	table.requestFocus();
	}

	public String getAllParameters(){

		StringBuffer sb = new StringBuffer();
		int rowCount = table.getRowCount();
		if(rowCount >0)
		{
			for(int i = 0; i < rowCount; i++)
			{
				String key = (String)table.getValueAt(i, 0);
				String unit = ((String)table.getValueAt(i, 1)  == null  ? "" : (String)table.getValueAt(i, 1) );
				String value = ((String)table.getValueAt(i, 2) == null  ? "" : (String)table.getValueAt(i, 2) );
				if( key != null)
				{
					sb.append(key+"="+unit+"="+value+";");
				}
			}
		}
		return sb.toString();
	}

	/**
	 *	This method updates the Attributes of the transition
	 */
	public void updateEdgeAttributes()
	{
		attributes.put( "transportLocations", getTransportTableData() );
		attributes.put( "value", "" );
		cell.changeAttributes( attributes );
	}

	/**
     * @return String
     * This method returns the TranportTable data separated by ";"
     * and rows separated by "#"
     */
    private String getTransportTableData()
    {
		StringBuffer sb = new StringBuffer();
		int rowCount 	= transportTable.getRowCount();
		if( rowCount > 0 )
		{
			for( int i = 0; i < rowCount; i++ )
			{
				String source 		= ( String )transportTable.getValueAt( i, 0 );
				String destination 	= ( String )transportTable.getValueAt( i, 1 );
				String normalTime 	= ( String )transportTable.getValueAt( i, 2 );
				if( normalTime.equals( "" ) )
                {
                    normalTime = "0";
                }
				String expressTime 	= ( String )transportTable.getValueAt( i, 3 );
				if( expressTime.equals( "" ) )
                {
                    expressTime = "0";
                }
				String normalCost 	= ( String )transportTable.getValueAt( i, 4 );
				if( normalCost.equals( "" ) )
                {
                    normalCost = "0";
                }
				String expressCost 	= ( String )transportTable.getValueAt( i, 5 );
				if( expressCost.equals( "" ) )
                {
                    expressCost = "0";
                }

				sb.append(source+";"+destination+";"+normalTime+";"+expressTime+";"+normalCost+";"+expressCost+"#");
			}
		}

		return sb.toString();
    }

    public void updateCellAttributes()
	{
		if( baseProcessType == null )
		{
			attributes.put( "Type", "" );
		}
		else
		{
			attributes.put( "Type", baseProcessType );
		}
		//attributes.put( "name", processNameField.getText() );
		//attributes.put( "value", processNameField.getText() + partNumberField.getText() );
		attributes.put( "value", processNameField.getText() );
		attributes.put( "partnumber", partNumberField.getText() );
		attributes.put( "dupPartNumbers", getDupPartNumbers() );
		attributes.put( "parameters", getAllParameters() );
		attributes.put( "comments",comments.getText() );
		attributes.put( "vendors" , getVendorData() );
        attributes.put ( "partStatus", partStatusField.getSelectedItem() );
        attributes.put ( "productGroup", productGroupField.getSelectedItem() );

        if( approvedProductPanel.isVisible() )
		{
			if( approvedCheckBox.getModel().isSelected() )
				attributes.put( "isApprovedProduct" , "true" );
			else
				attributes.put( "isApprovedProduct" , "false" );
		}
        if( isPrimaryFGPanel.isVisible() )
		{
			if( isPrimaryFGCheckBox.getModel().isSelected() )
				attributes.put( "isPrimaryFGProduct" , "true" );
			else
				attributes.put( "isPrimaryFGProduct" , "false" );
		}

		if( mktPanel.isVisible() )
		{
			attributes.put( "mktPartNumber", mktPartNumberField.getText() );
		}
		if( binRequiredPanel.isVisible() )
		{
			if( binsRequiredCheckBox.getModel().isSelected() )
				attributes.put( "binsRequired" , "true" );
			else
				attributes.put( "binsRequired" , "false" );
		}
		if( binPanel.isVisible() )
		{
			attributes.put( "goodBinNumber", goodBinField.getText().trim());
			attributes.put( "rejectedBinNumber", rejectedBinField.getText().trim() );
		}
		else
		{
			if( attributes.containsKey( "goodBinNumber" ) )
				attributes.remove( "goodBinNumber" );
			if( attributes.containsKey( "rejectedBinNumber" ) )
				attributes.remove( "rejectedBinNumber" );
		}
		cell.changeAttributes( attributes );
	}

    /**
     * @return
     */
    private String getVendorData()
    {
    	StringBuffer vendorsString = new StringBuffer();
		for( int j=0 ; j < vendorTable.getRowCount() ; j++  )
    	{
    		// This Condition is added to save only the Selected Vendors Data in XPDL file.
    		if( vendorTable.getModel().getValueAt( j , 0 ).equals( new Boolean("true")) )
    		{
				for( int i=0 ; i < vendorTable.getColumnCount() ; i++ )
	    		{
	    			if( vendorTable.getModel().getValueAt( j, i ) != null)
	    			{
	    				if( i == 0 )
	    				{
	    					if( vendorTable.getModel().getValueAt( j , i ).equals( new Boolean("false")) )
								vendorsString.append( "false" );
							else
								vendorsString.append( "true" );
	    				}
	    				else
	    				{
							vendorsString.append( vendorTable.getModel().getValueAt( j , i ));
	    				}
	    			}
					vendorsString.append(";");
	    		}
				vendorsString.deleteCharAt( vendorsString.length()-1 );
				vendorsString.append("#");
    		}
    	}
        return vendorsString.toString();
    }

    private String getDupPartNumbers()
    {
		StringBuffer sb = new StringBuffer();
		int rowCount 	= partNumberTable.getRowCount();
        if( rowCount > 0 )
		{
			for( int i = 0; i < rowCount; i++ )
			{
				if( partNumberTable.getValueAt(i, 0) != null && ( (String)partNumberTable.getValueAt(i, 0) ).length() > 0 )
				{
                    sb.append(((String)partNumberTable.getValueAt(i, 0)).trim()+";");
				}
			}
		}
        return sb.toString();
    }


	public void setVendorTable( String processType )
	{
		if( vendorTable.getColumnCount() < 1 )
		{
			vendorTable.addColumn( new TableColumn()	{
				public void setHeaderValue(Object headerValue){
					super.setHeaderValue("Select\n");
					setHeaderRenderer( renderer );
				}
			});

			vendorTable.addColumn( new TableColumn()	{
				public void setHeaderValue(Object headerValue){
					super.setHeaderValue("Priority\n");
					setHeaderRenderer( renderer );
				}
			});

			vendorTable.addColumn( new TableColumn()	{
				 public void setHeaderValue(Object headerValue){
					 super.setHeaderValue("Location\n");
					 setHeaderRenderer( renderer );
				 }
			 });
		 }

		 if( !processType.equalsIgnoreCase( "Wafer Store" ) && !processType.equalsIgnoreCase( "Die Bank" ) && !processType.equalsIgnoreCase( "Class Store" ) && !processType.equalsIgnoreCase( "Finished Goods" ))
		 {
			 if( vendorTable != null && vendorTable.getColumnCount() < 4 )
			 {
				 vendorTable.addColumn( new TableColumn()	{
					 public void setHeaderValue(Object headerValue){
						 super.setHeaderValue("Split\n(%)");
						 setHeaderRenderer( renderer );
					 }
				 });

				 vendorTable.addColumn( new TableColumn()	{
					 public void setHeaderValue(Object headerValue){
						 super.setHeaderValue("Capacity /\nWeek");
						 setHeaderRenderer( renderer );
					 }
				 });
                /*
				 vendorTable.addColumn( new TableColumn()	{
					 public void setHeaderValue(Object headerValue){
						 super.setHeaderValue("UnitCost\nNormal($)");
						 setHeaderRenderer( renderer );
					 }
				 });

				 vendorTable.addColumn( new TableColumn()	{
					 public void setHeaderValue(Object headerValue){
						 super.setHeaderValue("UnitCost\nExpress($)");
						 setHeaderRenderer( renderer );
					 }
				 });
                 */
				 /*vendorTable.addColumn( new TableColumn()	{
					 public void setHeaderValue(Object headerValue){
						 super.setHeaderValue("CycleTime\nNormal");
						 setHeaderRenderer( renderer );
					 }
				 });

				 vendorTable.addColumn( new TableColumn()	{
					 public void setHeaderValue(Object headerValue){
						 super.setHeaderValue("CycleTime\nExpress");
						 setHeaderRenderer( renderer );
					 }
				 });*/
                 /*
				 vendorTable.addColumn( new TableColumn()	{
					 public void setHeaderValue(Object headerValue){
						 super.setHeaderValue("Expected\nYield(%)");
						 setHeaderRenderer( renderer );
					 }
				 }); */
			 }
		 }
		 else
		 {
			 while( vendorTable.getColumnCount() > 3 )
			 {
				 vendorTable.removeColumn( vendorTable.getColumnModel().getColumn(3));
			 }
		 }
	 }

	private Vector getColumnIdentifiers( JTable table )
	{
		Vector colIdentifiers = new Vector();
		for( int i=0; i < table.getColumnCount() ;i++)
		{
			colIdentifiers.add( table.getColumnModel().getColumn(i).getIdentifier());
		}
		return colIdentifiers;
	}

	private void getNewDefaultParameters( Vector data, String processType )
	{
		//Vector defaultParameterList  = ParameterTypes.getDefaultParameters( processType );
		Vector defaultParameterList  = null;

		if( processParametersMap.containsKey( processType ) && ( ( HashMap ) processParametersMap.get( processType ) ).containsKey( "parameters" ) )
		{
			defaultParameterList  = (Vector)( ( HashMap ) processParametersMap.get( processType ) ).get( "parameters" );
		}

		if( defaultParameterList != null && defaultParameterList.isEmpty() == false )
		{
			Iterator it = defaultParameterList.iterator();
			while ( it.hasNext() )
			{
				Vector defaultParameterVector = (Vector) it.next();
				if( defaultParameterVector != null && defaultParameterVector.isEmpty() == false )
				{
					addDefaultParameter( data, defaultParameterVector );
				}
			}
		}
	}

	private void addDefaultParameter( Vector dataList, Vector defaultParameterVector )
	{
		String parameter =  (String)defaultParameterVector.get( 0 );
        if(parameter != null)
        {
            parameter = parameter.trim() ;
        }
        String daraListParameter = "";
        boolean present  =  false;

		if( dataList != null && dataList.isEmpty() == false )
		{
			Iterator it = dataList.iterator();
			while ( it.hasNext() )
			{
                Vector parameterVector = (Vector) it.next();
				if( parameterVector != null && parameterVector.isEmpty() == false )
				{
                    daraListParameter = (String)parameterVector.get(0);
                    if(daraListParameter != null)
                    {
                        daraListParameter = daraListParameter.trim();
                    }
                    if( parameter.equalsIgnoreCase( daraListParameter ))
					{
						present = true;
						break;
					}
				}
			}

			if( !present )
			{
				dataList.add( defaultParameterVector );
			}
		}
	}

    private String chkUnSavedPartNumbers()
    {
        String dupPartNumbers 	= "";
        ArrayList existingPartNumbersList = new ArrayList (5);

        //String cellAttID = "";
        //if ( attributes.get("attrId") != null )
        //{
        //    cellAttID = (String)attributes.get("attrId");
        //}

        ArrayList list = graph.getWorkflowManager().getActivities();

        for( int i = 0; i < list.size(); i++ )
        {
            DefaultGraphCell cell 	= ( DefaultGraphCell )list.get( i );
            Map map 				= cell.getAttributes();
            String curProcessType = (String)map.get("Type");
            //String curProcessAttID = (String)map.get("attrId");

            if ( curProcessType != null && curProcessType.equalsIgnoreCase( baseProcessType ) )
            {
                //if (curProcessAttID != null && cellAttID != null && curProcessAttID.equalsIgnoreCase( cellAttID) )
                //{
                //    continue;
                //}

                //if ( this.cell == cell || this.cell.hashCode() == cell.hashCode() )
                if ( this.cell == cell )
                {
                    continue;
                }

                String curProcessPartNumber = (String)map.get("partnumber");
                if ( curProcessPartNumber != null && curProcessPartNumber.length() > 0)
                {
                    if ( ! existingPartNumbersList.contains(curProcessPartNumber) )
                    {
                        existingPartNumbersList.add( curProcessPartNumber );
                    }
                }

                String curProcessDupliPartNumbers = (String)map.get("dupPartNumbers");
                ArrayList duplicatePNList = new ArrayList(5);
                if ( curProcessDupliPartNumbers != null && curProcessDupliPartNumbers.length() > 0 )
                {
                   duplicatePNList = graph.getWorkflowManager().parseString( curProcessDupliPartNumbers , ';' );
                }

                for (int idx=0; idx<duplicatePNList.size(); idx++ )
                {
                    if ( duplicatePNList.get(idx) != null && ( (String)duplicatePNList.get(idx) ).trim().length() > 0 )
                    {
                        if ( ! existingPartNumbersList.contains(duplicatePNList.get(idx)) )
                        {
                            existingPartNumbersList.add( duplicatePNList.get(idx) );
                        }
                    }
                }
            }
        }

        ArrayList partNumberList = new ArrayList(5);
        if ( partNumberField.getText() != null && partNumberField.getText().length() > 0 )
        {
            partNumberField.setText( partNumberField.getText().trim());
            partNumberList.add( partNumberField.getText() );
        }

        int rowCount = partNumberTable.getRowCount();

        if( rowCount > 0 )
        {
            for( int i = 0; i < rowCount; i++ )
            {
                if( partNumberTable.getValueAt(i, 0) != null && ( (String)partNumberTable.getValueAt(i, 0) ).length() > 0 )
                {
                    partNumberTable.getModel().setValueAt( ((String)partNumberTable.getValueAt(i, 0)).trim() , i, 0);
                    partNumberList.add( ( String ) partNumberTable.getValueAt( i, 0 ) );
                }
            }
        }

        for (int i=0; i < partNumberList.size(); i++ )
        {
            String partNumber = ((String)partNumberList.get(i));
            for (int j=0; j < existingPartNumbersList.size(); j++ )
            {
                String existingPartNumber = ((String)existingPartNumbersList.get(j));
                if ( partNumber.equalsIgnoreCase( existingPartNumber) )
                {
                    dupPartNumbers = dupPartNumbers + partNumber + ";";
                }
            }
        }

        if ( dupPartNumbers != null && dupPartNumbers.length() > 0)
        {
            dupPartNumbers.endsWith(";");
            dupPartNumbers = dupPartNumbers.substring(0, dupPartNumbers.length() - 1 );
        }

        return dupPartNumbers;
    }

    /**
     * @return marketingPartNumber
     * This method checks wethere this process's marketing part number assigned to another process
     * if so it returns marketing part number, otherwise empty string.
     */
    private String chkForMarketingPartNumber()
    {
        boolean exists = false;
        String marketingPartNumber 	= "";

        if ( mktPartNumberField.getText() != null && mktPartNumberField.getText().length() > 0 )
        {
            marketingPartNumber = mktPartNumberField.getText().trim();
            mktPartNumberField.setText( marketingPartNumber );
        }

        ArrayList existingMarketingNumberList = new ArrayList (5);
        ArrayList list = graph.getWorkflowManager().getActivities();

        for( int i = 0; i < list.size(); i++ )
        {
            DefaultGraphCell cell 	= ( DefaultGraphCell )list.get( i );
            Map map 				= cell.getAttributes();
            String curProcessType = (String)map.get("Type");

            if ( curProcessType != null && curProcessType.equalsIgnoreCase( baseProcessType ) )
            {
                if ( this.cell == cell )
                {
                    continue;
                }

                String curProcessMarketingPartNumber = (String)map.get("mktPartNumber");
                if ( curProcessMarketingPartNumber != null && curProcessMarketingPartNumber.length() > 0)
                {
                    if ( ! existingMarketingNumberList.contains(curProcessMarketingPartNumber) )
                    {
                        existingMarketingNumberList.add( curProcessMarketingPartNumber );
                    }
                }
            }
        }

        for (int i=0; i < existingMarketingNumberList.size(); i++ )
        {
            String existingMarketingPartNumber = ((String)existingMarketingNumberList.get(i));

            if ( marketingPartNumber.equalsIgnoreCase( existingMarketingPartNumber ) )
            {
                    exists = true;
                    break;
            }
        }

        if ( !exists )
        {
            marketingPartNumber = "";
        }

        return marketingPartNumber;
    }

    private void getVendorsWithLots( String processStepId )
    {
		URL url;								                        // URL to connect.
		URLConnection con 	= null;				                        // Connection Object to connect to URL.
		String str = "vendorsWithLosts" + separator + processStepId;	// This is the key specifying the DATA required.
		ObjectOutputStream outStream 	= null;                         // Byte Stream to write into
		ObjectInputStream inputToApplet = null;	                        // Byte Stream to read from

		try
		{
			// Connect to com.scalar.chiptrack.operations.process.WorkFlowAction
			// The servlet used to fetch data
			url = new URL( graph.editor.getContextURL()+ "/WorkflowServlet");
			// Open the Connection to the URL
			con = url.openConnection();

			if ( !con.getDoOutput() )
			{
				con.setDoOutput( true );
			}
			con.setDoInput( true );
			con.setUseCaches ( false );
			con.setDefaultUseCaches ( false );
			con.setAllowUserInteraction( true );
			// Set the Content length to the length of data u supose to write to Connection
			con.setRequestProperty ( "CONTENT_LENGTH", "" + str.length() );
			con.setRequestProperty ( "Content-Type", "application/octet-stream" );
			// Connect to the URL
			con.connect();
			// Get the ObjectOutputStream send information to servlet
			outStream = new ObjectOutputStream( con.getOutputStream() );
			// Write the required information to the ObjectOutputStream.
			outStream.writeObject( str );
			outStream.flush();
			outStream.close();

			// Fetch the ObjectInputStream from the connection.
			inputToApplet = new ObjectInputStream( con.getInputStream() );
			try
			{
				// Read the information Fetched from the Servlet
				vendorsWithLots = (ArrayList) inputToApplet.readObject();
			}
			catch ( ClassNotFoundException e2 )
			{
				e2.printStackTrace();
			}
			// Close the InputStream.
			inputToApplet.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
        return;
    }

    public static Map getActivityAttributesMap( String processStepId, WorkflowGraph graph )
    {
        URL url;								                        // URL to connect.
		URLConnection con 	= null;				                        // Connection Object to connect to URL.
		String str = "loadActivityAttributes" + separator + processStepId;	// This is the key specifying the DATA required.
		ObjectOutputStream outStream 	= null;                         // Byte Stream to write into
		ObjectInputStream inputToApplet = null;	                        // Byte Stream to read from
        Map activityAttributesMap = null;
		try
		{
			// Connect to com.scalar.chiptrack.operations.process.WorkFlowAction
			// The servlet used to fetch data
			url = new URL( graph.editor.getContextURL()+ "/WorkflowServlet");
			// Open the Connection to the URL
			con = url.openConnection();

			if ( !con.getDoOutput() )
			{
				con.setDoOutput( true );
			}
			con.setDoInput( true );
			con.setUseCaches ( false );
			con.setDefaultUseCaches ( false );
			con.setAllowUserInteraction( true );
			// Set the Content length to the length of data u supose to write to Connection
			con.setRequestProperty ( "CONTENT_LENGTH", "" + str.length() );
			con.setRequestProperty ( "Content-Type", "application/octet-stream" );
			// Connect to the URL
			con.connect();
			// Get the ObjectOutputStream send information to servlet
			outStream = new ObjectOutputStream( con.getOutputStream() );
			// Write the required information to the ObjectOutputStream.
			outStream.writeObject( str );
			outStream.flush();
			outStream.close();
            outStream = null;

            // Fetch the ObjectInputStream from the connection.
			inputToApplet = new ObjectInputStream( con.getInputStream() );
			try
			{
				// Read the information Fetched from the Servlet
				activityAttributesMap = (Map) inputToApplet.readObject();
			}
			catch ( Exception e2 )
			{
				e2.printStackTrace();
			}
		}
		catch ( Exception e )
		{
			e.printStackTrace();
		}
        finally
        {
            if ( outStream != null )
            {
                try { outStream.close(); outStream = null; } catch ( IOException ignore ) {}
            }
            if ( inputToApplet != null )
            {
                try { inputToApplet.close(); inputToApplet = null; } catch ( IOException ignore ) {}
            }
        }
        return activityAttributesMap;
    }
    private String saveAttributesInDB()
    {
        URL url;								                        // URL to connect.
		URLConnection con 	= null;				                        // Connection Object to connect to URL.
		String str = "saveActivityAttributes";// + separator + graph.getEditor().getName();	// This is the key specifying the DATA required.
        attributes.put( "baseProductName", graph.getEditor().getName() );
        ObjectOutputStream outStream 	= null;                         // Byte Stream to write into
		ObjectInputStream inputToApplet = null;	                        // Byte Stream to read from
        String processStepId = "";
		try
		{
			// Connect to com.scalar.chiptrack.operations.process.WorkFlowAction
			// The servlet used to fetch data
			url = new URL( graph.editor.getContextURL()+ "/WorkflowServlet");
			// Open the Connection to the URL
			con = url.openConnection();

			if ( !con.getDoOutput() )
			{
				con.setDoOutput( true );
			}
			con.setDoInput( true );
			con.setUseCaches ( false );
			con.setDefaultUseCaches ( false );
			con.setAllowUserInteraction( true );
			// Set the Content length to the length of data u supose to write to Connection
			con.setRequestProperty ( "CONTENT_LENGTH", "" + str.length() );
			con.setRequestProperty ( "Content-Type", "application/octet-stream" );
			// Connect to the URL
			con.connect();
			// Get the ObjectOutputStream send information to servlet
			outStream = new ObjectOutputStream( con.getOutputStream() );
			// Write the required information to the ObjectOutputStream.
			outStream.writeObject( str );
			outStream.writeObject( attributes );
			outStream.flush();
			outStream.close();
            outStream = null;

            // Fetch the ObjectInputStream from the connection.
			inputToApplet = new ObjectInputStream( con.getInputStream() );
			try
			{
				// Read the information Fetched from the Servlet
				processStepId = (String) inputToApplet.readObject();
			}
			catch ( Exception e2 )
			{
				e2.printStackTrace();
			}
		}
		catch ( Exception e )
		{
			e.printStackTrace();
		}
        finally
        {
            if ( outStream != null )
            {
                try { outStream.close(); outStream = null; } catch ( IOException ignore ) {}
            }
            if ( inputToApplet != null )
            {
                try { inputToApplet.close(); inputToApplet = null; } catch ( IOException ignore ) {}
            }
        }
        return processStepId;
    }
}